Check if a Numpy Array is in ascending order

This tutorial will discuss about unique ways to check if a numpy array is sorted in ascending order.

Table Of Contents

Method 1: Using numpy.diff()

We can use the numpy.diff() method to check if a NumPy array is sorted in ascending order. The numpy.diff() method accepts an array as an argument, and returns an array containing the difference between every consequitive element. Basically it will return an array containing n-th discrete difference along the given axis. For example, if we pass an array arr to the diff() methid, then it will return an array out. Where,

out[i] = arr[i+1] - arr[i]

The ith element of returned array will be the difference between ithand (i+1)th element of passed numpy array.

Then we can check if all the values in the returned array are greater than or equal to zero. If yes, then it means that the array is sorted in ascending order.

Let’s see the complete example,

import numpy as np

# Create a NumPy Array
arr = np.array([21, 32, 43, 57, 88])

# Check if array is sorted in ascending order
if np.all(np.diff(arr) >= 0):
    print("The NumPy Array is sorted in ascending order")
else:
    print("The NumPy Array is not sorted in ascending order")

Output

The NumPy Array is sorted in ascending order

Method 2: Using all() method

Iterate over all the elements of NumPy array by the index position. Check if any element is greater than or equal to the element next to it. If yes, then it means array is not sorted, otherwise array is sorted in ascending order.

Let’s see the complete example,

import numpy as np

# Create a NumPy Array
arr = np.array([21, 32, 43, 57, 88])

# Check if array is sorted in ascending order
if all(arr[i] <= arr[i+1] for i in range(len(arr)-1)):
    print("The NumPy Array is sorted in ascending order")
else:
    print("The NumPy Array is not sorted in ascending order")

Output

The NumPy Array is sorted in ascending order

Summary

We learned about two ways to check if a NumPy array is sorted in ascending order. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top