Sorting an array
Using lists
Python provides an iterator to sort an array sorted()
you can use it this way :
import random
# Random lists from [0-999] interval
arr = [random.randint(0, 1000) for r in range(10)]
print(f'Initial random list : {arr}\n')
reversed_arr = list(sorted(arr))
print(f'Sorted list : {reversed_arr}')
Initial random list : [277, 347, 976, 367, 604, 878, 148, 670, 229, 432]
Sorted list : [148, 229, 277, 347, 367, 432, 604, 670, 878, 976]
it is also possible to use the sort function from the list object
# Random lists from [0-999] interval
arr = [random.randint(0, 1000) for r in range(10)]
print(f'Initial random list : {arr}\n')
arr.sort()
print(f'Sorted list : {arr}')
Initial random list : [727, 759, 68, 103, 23, 90, 258, 737, 791, 567]
Sorted list : [23, 68, 90, 103, 258, 567, 727, 737, 759, 791]
Using numpy
If you are using numpy you can sort an array by creating a view on the array:
import numpy as np
arr = np.random.random(5)
print(f'Initial random array : {arr}\n')
sorted_arr = np.sort(arr)
print(f'Sorted array : {sorted_arr}')
Initial random array : [0.40021786 0.13876208 0.19939047 0.46015169 0.43734158]
Sorted array : [0.13876208 0.19939047 0.40021786 0.43734158 0.46015169]