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:
- Insertion Sort
- Selection Sort
- Merge Sort
- 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.
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.
Getting the Error as ‘a is NOT DEFINED’. Why am I getting these error.
a is a variable here that represents a NumPy array, so you must have forgotten to create a Numpy array.