Sort NumPy Arrays using Python

Being a computer science student you must have gone through the concept of sorting algorithms. In Python, we use sorting algorithms to sort items in a list. But what if we want to sort NumPy arrays? In this article, I will take you through how to sort NumPy arrays using Python.

Sorting NumPy Arrays

There are a bunch of sorting algorithms in computer science, for example:

  1. Insertion Sort
  2. Selection Sort
  3. Merge Sort
  4. Bubble Sort and many more.

All of these algorithms are used to sort values in a list or an array. The NumPy library provides an inbuild function for sorting the values inside a NumPy array. Below is how we sort a NumPy array by using the inbuilt sort function:

import numpy as np
a = np.array([34, 5, 89, 23, 76])
print(np.sort(a))

The sort function in the NumPy library works the same as the sort function in the Python programming language. But, what if we want to write a sorting algorithm to sort a NumPy array using Python without using the sort function? In the section below, I will take you through how to sort NumPy arrays using Python.

Sort NumPy Arrays using Python

Sorting values in a data structure is one of the favourite topics of coding interviews. NumPy array is also a data structure like a list or an array, so you should also know how to sort the values of a NumPy array using Python without using any sort function. Below is how to sort a NumPy array using Python:

def sorting(x):
    for i in range(len(x)):
        swap = i + np.argmin(x[i:])
        (x[i], x[swap]) = (x[swap], x[i])
    return x
print(sorting(a))

Also, Read – Python Projects with Source Code: Solved and Explained.

Conclusion

The above algorithm is based on the selection sort. It is a very common algorithm for sorting values in a data structure. I hope you liked this article on how to sort values of a NumPy array using Python without using any inbuilt function. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

Data Strategist at Statso. My aim is to decode data science for the real world in the most simple words.

Articles: 1840

2 Comments

Leave a Reply

Discover more from thecleverprogrammer

Subscribe now to keep reading and get access to the full archive.

Continue reading