Array Sorting Using Numpy in Python

Filed Under: NumPy
Array Sorting In Numpy

Numerical Python, in short Numpy, is a comprehensive package in python used for scientific computations. Usually, all those scientific computations require much time and code. But, Numpy will help us in more efficient computations with less code. Today, we are here to discuss Array sorting using Numpy in Python. Excited?! Don’t stop!!!

A bit about Numpy

  • Numpy was started as an open source project in 2005 by Mr. Oliphant.
  • Most renowned and robust library for array computations in Python.
  • It can deal with linear algebra, Fourier transform and matrices.
  • Needless to say, Numpy – Numerical Python. 馃槢

Numpy Installation and Basic Array Sorting

First things first! Let’s install the Numpy library into python and get started. Run the below which will install and load Numpy into Python.

#Install and load Numpy in Python

pip install numpy

import numpy as np

Perfect! Now let’s a sample array using Numpy and see how we can sort it in less than 2 lines of code.


#Basic array sorting using numpy

import numpy as np
sample_array = np.array([3,1,2,4,6,5])
[1 2 3 4 5 6]
  • As shown above, you can use np.sort function in Numpy to sort the arrays easily.


#numpy argsort

my_array = np.array([2,1,3,4,5])
output_array = np.argsort(my_array)

array([1, 0, 2, 3, 4], dtype=int64)
  • In NumPy np.argsort, the resultant array is the index number of the items in NumPy in ascending order.

array sorting

Array Sorting with Different Datatypes

In this section, let’s see how we can sort the arrays with different data types. We will be looking into multiple examples as one includes string and Boolean data types.

#String data type

import numpy as np
sample_array = np.array(['Jan','Sep','Aug','Mar','Dec'])
['Aug' 'Dec' 'Jan' 'Mar' 'Sep']

The array with string data has been sorted as expected!

Now, let’s try with a Boolean data type.

#Bool data type 

import numpy as np
sample_array = np.array([True, False, True, False, False])
[False False False  True  True]

That’s perfect! I hope things are much clear now for you.

Some Sorting Algorithms with Numpy

The sorting algorithms are the basic and vital part of any computer science course. If you are from a CS background, you know it well :P.

Now, let’s look into some sorting algorithms such as selection sort and Bogo sort. Without wasting much time, let’s see what these sorts are about.

Selection sort using Numpy

  • It is kind of a comparison sorting algorithms used to sort random items in a list of an array.
  • Selection sort is best known for it’s simplicity.
  • But, it will be too slow for large arrays.
  • The sorting iterations are based on the items count in the array and execution time will be square of the number of items. So, if you keep add the items into an array, the execution time will go up and up.

Enough theory, Time to Code!

#Selection sort algorithm using numpy 

import numpy as np

#Define customer function 

def selection_sort(my_array):
     for i in range(len(my_array)):
            swap = i + np.argmin(my_array[i:])
            (my_array[i], my_array[swap]) = (my_array[swap], my_array[i])
            return my_array

#Create an array
my_array = ([2,1,3,4,5])

#Pass the array to customer function 
array([1, 2, 3, 4, 5])

There you have it!

Bogo sort using Numpy

  • It will random shuffle the items until the outcome seems to be sorted.
  • This algorithm just relies on random chance.
  • It will iterate n times till it feel the array is sorted.
#Bogo sort algorithm using numpy 

import numpy as np

def bogosort(my_array):
    while np.any(my_array[:-1] > my_array[1:]):
        return my_array
my_array = np.array([2,1,4,3,5])

These are some of the traditional sorting algorithms which take some time to execute. But as already discussed above, you can numpy built-in functions such as np.sort() and np.argsort() for faster array sorting.

Final Words – Array sorting

Numpy is one of the most vital libraries in python used for scientific computations. We have come across traditional sorting algorithms such as selection sort and BOGO sort. Also, we found that built-in numpy sorting functions such as np.sort and np.argsort are much faster and effective.

So, this is all about array sorting in numpy. Keep an eye on upcoming discussions for more topics. Till then, Happy Python 馃檪

More read:

Numpy documentation

Numpy sorting

Generic selectors
Exact matches only
Search in title
Search in content