How to get the sorted array and indices in Python without importing additional modules like Numpy
the power of lambda functions
Matlab’s sort is so convenient that it returns both the sorted array and the sorted indices.
With Numpy, one can obtain the sorted indices by using argsort and then get the sorted array by doing sorted_array = array[sorted_indices].
However, if importing modules is not allowed, the Pythonic approach is to zip the array and the unsorted indices and invoke sorted:
array = [9, 8, 3, 6, 8]
sorted_array_and_indices = sorted(zip(array, range(len(array))), key=lambda x:x[0])
sorted_array, sorted_indices = map(list, zip(*sorted_array_and_indices))
# sorted_array is [3, 6, 8, 8, 9]
# sorted_indices is [2, 3, 1, 4, 0]
# `sorted` is stable
A perhaps more clever approach is to sort the unsorted indices according to the array elements:
array = [9, 8, 3, 6, 8]
sorted_indices = sorted(range(len(array)), key=lambda x:array[x])
sorted_array = [array[index] for index in sorted_indices]
# sorted_array is [3, 6, 8, 8, 9]
# sorted_indices is [2, 3, 1, 4, 0]
Enjoy Reading This Article?
Here are some more articles you might like to read next: