Skip to Content

Numpy – Check If Array is Sorted

In this tutorial, we will look at how to check if a numpy array is sorted or not with the help of some examples.

You can use the following methods to check if a numpy array is sorted (for example, in ascending order) or not –

  1. Iterate through the array elements and check if the current element is greater than equal to the previous element. If any element violates this condition, we can say that the array is not sorted in ascending order.
  2. Compare the original array with a copy of the sorted array and check if all the corresponding values are equal or not.

Let’s now look at the two methods with the help of some examples –

Method 1 – Check array is sorted by iterating

The idea is to iterate through the array elements (starting at index 1) and check if each element is greater than or equal to the previous element. If this is the case for all the elements, we can say that the array is sorted in ascending order.

We can write a simple Python function to implement this –

# function to check if array is sorted in ascending order
def is_sorted_asc(ar):
    for i in range(1, len(ar)):
        if ar[i-1] <= ar[i]:
            continue
        else:
            return False
    return True

Let’s now apply this to a couple of arrays.

import numpy as np

# create two arrays
ar1 = np.array([1, 2, 2, 4, 5, 7])
ar2 = np.array([2, 3, 5, 4, 1])

# check if array is sorted in ascending order
print(is_sorted_asc(ar1))
print(is_sorted_asc(ar2))

Output:

True
False

We get True for ar1 and False for ar2 which are the correct outputs. The array ar1 is sorted in ascending order and the array ar2 is not sorted.

We can similarly, use this logic to check if the array is sorted in descending order or not. Here, check if each element is smaller than (or equal to) the previous element in the array.

# function to check if array is sorted in descending order
def is_sorted_desc(ar):
    for i in range(1, len(ar)):
        if ar[i-1] >= ar[i]:
            continue
        else:
            return False
    return True

Let’s apply the above function to a couple of sample arrays.

import numpy as np

# create two arrays
ar1 = np.array([7, 5, 4, 3, 3, 2])
ar2 = np.array([5, 4, 1, 3])

# check if array is sorted in descending order
print(is_sorted_desc(ar1))
print(is_sorted_desc(ar2))

Output:

True
False

We get the correct output.

Method 2 – Compare array to sorted array

In this method, we sort the original array and store it in a variable and compare the original array with the sorted array. If all the corresponding elements are equal, we can say that the original array is sorted.

You can use the numpy.sort() function which returns a sorted copy of a numpy array and the numpy all() function to check if all the values in the array are True or not.

Let’s first see how to check if the array is sorted in ascending order or not.

import numpy as np

# create two arrays
ar1 = np.array([1, 2, 2, 4, 5, 7])
ar2 = np.array([2, 3, 5, 4, 1])

# check if array is sorted in ascending order
print((ar1 == np.sort(ar1)).all())
print((ar2 == np.sort(ar2)).all())

Output:

True
False

We get the correct result (same as what we got in Method – 1)

We can similarly check if the array is sorted in descending order or not. For this, sort the array in ascending order using numpy.sort() function and then reverse it using slicing [::-1].

import numpy as np

# create two arrays
ar1 = np.array([7, 5, 4, 3, 3, 2])
ar2 = np.array([5, 4, 1, 3])

# check if array is sorted in descending order
print((ar1 == np.sort(ar1)[::-1]).all())
print((ar2 == np.sort(ar2)[::-1]).all())

Output:

True
False

We get the correct result.

Note this method has a higher time complexity O(nlogn) since we are sorting the array as against method 1 which is linear in time complexity.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Authors

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

  • Tushar Mahuri