07/02/2025, 21:13 numpy_sorting
In [6]: import numpy as np
x= np.arange(10)
print(np.argmax(x[5:])) # argmin and argmax gives lowest number index and highe
print(x[:-1])
np.random.shuffle(x)
print(x)
4
[0 1 2 3 4 5 6 7 8]
[3 2 1 7 5 8 4 0 6 9]
In [ ]: # bubble sort :
import numpy as np
def selection_sort(x):
for i in range(len(x)):
swap = i + np.argmin(x[i:])
(x[i], x[swap]) = (x[swap], x[i])
return x
x = np.array([2, 1, 4, 3, 5])
print(selection_sort(x))
In [7]: # bogosort (selection sort) :
def bogosort(x):
while np.any(x[:-1] > x[1:]):
np.random.shuffle(x)
return x
x=np.array([2, 1, 4, 3, 5])
print(bogosort(x))
[1 2 3 4 5]
In [8]: # fast sorting in numpy : np.sort and np.argsort :
# Although Python has built-in sort and sorted functions to work with lists, we
# discuss them here because NumPy’s np.sort function turns out to be much more
# efficient and useful for our purposes. By default np.sort uses an O(N log N),
# sort algorithm, though mergesort and heapsort are also available. For most app
# the default quicksort is more than sufficient.
x = np.array([2, 1, 4, 3, 5])
print(np.sort(x)) # or u can use x.sort()
# A related function is argsort, which instead returns the indices of the sorted
# elements:
i = np.argsort(x)
print(i)
[1 0 3 2 4]
In [15]: # Sorting along rows or columns :
np.random.seed(0)
X = np.random.randint(0, 10, (4, 6))
print(X)
# sort each column of X
print(np.sort(X, axis=0))
# sort each row of X
print(np.sort(X, axis=1))
localhost:8924/doc/workspaces/auto-u/tree/numpy_sorting.ipynb 1/2
07/02/2025, 21:13 numpy_sorting
[[5 0 3 3 7 9]
[3 5 2 4 7 6]
[8 8 1 6 7 7]
[8 1 5 9 8 9]]
[[3 0 1 3 7 6]
[5 1 2 4 7 7]
[8 5 3 6 7 9]
[8 8 5 9 8 9]]
[[0 3 3 5 7 9]
[2 3 4 5 6 7]
[1 6 7 7 8 8]
[1 5 8 8 9 9]]
In [16]: # Partial Sorts: Partitioning
# NumPy provides this in the np.partition function.
# np.partition takes an array and a number K; the result is a new array with the
# K values to the left of the partition, and the remaining values to the right,
x = np.array([7, 2, 3, 1, 6, 5, 4])
print(np.partition(x, 3))
# Note that the first three values in the resulting array are the three smallest
# array, and the remaining array positions contain the remaining values. Within
# two partitions, the elements have arbitrary order.
print(np.partition(X, 2, axis=1))
[2 1 3 4 6 5 7]
[[0 3 3 5 7 9]
[2 3 4 5 7 6]
[1 6 7 8 8 7]
[1 5 8 9 8 9]]
localhost:8924/doc/workspaces/auto-u/tree/numpy_sorting.ipynb 2/2