Python | Returning index of a sorted list
Sort a list in python and then return the index of elements in sorted order.
Examples:
Input : [2, 3, 1, 4, 5] Output : [2, 0, 1, 3, 4] After sorting list becomes [1, 2, 3, 4, 5] and their index as [2, 0, 1, 3, 4] Input : [6, 4, 7, 8, 1] Output : [4, 1, 0, 2, 3] After sorting the list becomes [1, 4, 6, 7, 8] and their index as [4, 1, 0, 2, 3].
Method 1
Python
import numpy s = numpy.array([ 2 , 3 , 1 , 4 , 5 ]) sort_index = numpy.argsort(s) print (sort_index) |
Output :
[2, 0, 1, 3, 4]
Time Complexity: O(n*log(n))
Auxiliary Space: O(n)
Method 2
Python
s = [ 2 , 3 , 1 , 4 , 5 ] li = [] for i in range ( len (s)): li.append([s[i],i]) li.sort() sort_index = [] for x in li: sort_index.append(x[ 1 ]) print (sort_index) |
Output:
[2, 0, 1, 3, 4]
Time Complexity: O(n*log(n))
Auxiliary Space: O(n)
Method #3: Using the built-in sorted() function along with enumerate() function
Python3
s = [ 2 , 3 , 1 , 4 , 5 ] # Using the built-in sorted() function along with enumerate() function # enumerate() returns a tuple (index, value) for each element in the list # and sorted() sorts the list based on the value sort_index = [i for i, x in sorted ( enumerate (s), key = lambda x: x[ 1 ])] print (sort_index) #This code is contributed by Edula Vinay Kumar Reddy |
[2, 0, 1, 3, 4]
This method uses the built-in sorted() function which takes an iterable (in this case, the enumerate of the original list) and sorts it based on a key function (in this case, the lambda function that accesses the second element of each tuple returned by enumerate). The [i for i, x in …] list comprehension then iterates through the sorted enumerate and appends the first element (the index) of each tuple to the sort_index list.
Time Complexity: O(n*log(n))
Auxiliary Space: O(n)
Please Login to comment...