0% found this document useful (0 votes)
19 views

Sort

The document discusses different ways to sort a NumPy array in Python including sorting along axes, none axis, and using different sorting algorithms like quicksort, mergesort, and heapsort.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Sort

The document discusses different ways to sort a NumPy array in Python including sorting along axes, none axis, and using different sorting algorithms like quicksort, mergesort, and heapsort.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Practice | GeeksforGeeks | A computer science portal ... https://www.geeksforgeeks.org/batch/fork-data-scienc...

1 sur 3 11/04/2024 10:50


Practice | GeeksforGeeks | A computer science portal ... https://www.geeksforgeeks.org/batch/fork-data-scienc...

Array Sorting

There are multiple ways in Numpy to sort an array, based on the requirement
using Python. Let’s try to understand them with the help of di�erent methods. In
this article, we will see How to sort a Numpy Array in Python.

Sort a Numpy Array using the sort()


Here we sort the given array based on the axis using the sort() method i.e. create
a sorted copy of the given numpy array.

Python3

import numpy as np

# sort along the first axis


a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = 0)
print ("Along first axis : \n", arr1)

# sort along the last axis


a = np.array([[10, 15], [12, 1]])
arr2 = np.sort(a, axis = -1)
print ("\nAlong first axis : \n", arr2)

a = np.array([[12, 15], [10, 1]])


arr1 = np.sort(a, axis = None)
print ("\nAlong none axis : \n", arr1)

Output:

Along first axis :


[[10 1]
[12 15]]

Along first axis :


[[10 15]
[ 1 12]]

2 sur 3 11/04/2024 10:50


Practice | GeeksforGeeks | A computer science portal ... https://www.geeksforgeeks.org/batch/fork-data-scienc...

Along none axis :


[ 1 10 12 15]

We can choose which type of sorting we want perform using the kind parameter
inside the sort function. We can either choose between quicksort, mergesort and
heapsort.

Python3

arr = np.array([[7,3,8,6,4], [7,2,9,8,6],[5,4,2,3,1]])


print(np.sort(arr , axis = 0, kind = 'mergesort'))
print()
print(np.sort(arr , axis = 1, kind = 'quicksort'))
print()
print(np.sort(arr , kind = 'heapsort'))

Output:

[[5 2 2 3 1]
[7 3 8 6 4]
[7 4 9 8 6]]

[[3 4 6 7 8]
[2 6 7 8 9]
[1 2 3 4 5]]

[[3 4 6 7 8]
[2 6 7 8 9]
[1 2 3 4 5]]

3 sur 3 11/04/2024 10:50

You might also like