2 Ways to Check if a Numpy 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. Compute the difference between the (i+1)th value and ith value in the array and check if all such differences are greater than equal to zero.

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

### Method 1 – Check array is sorted by iterating

Here, we iterate over the array elements and check if each element is greater than or equal to the previous element, if all the elements satisfy this condition, we say that the array is sorted in ascending order.

import numpy as np

create two arrays

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

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

check if array is sorted in ascending order

print(is_sorted_asc(ar1)) print(is_sorted_asc(ar2))

Output:

True False

Here, we created a function to check if the array is sorted in ascending order or not.

### Using the numpy.diff() function

The numpy.diff() function returns the one-step difference (by default) for each value in a numpy array. The one-step difference is the difference between the (i+1)th and the ith value in the array.

Now, if all such differences in a numpy array are greater than or equal to zero, we can say that the array is sorted in ascending order.

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

print((np.diff(ar1) >= 0).all()) print((np.diff(ar2) >= 0).all())

Output:

True False

Here, we used the numpy array all() function to check if all the differences are greater than or equal to zero or not.

NOTE: There are many ways to check if a numpy array is sorted or not for ex: Comparing the array to a sorted copy you can let me know if you know more ways.