Terence Ng
Terence Ng

Reputation: 17

Implement Selection Sort in a specific index in a nested list

I am able to implement selection sort for every first value of a list, so e.g. list[0][0], list[1][0], list[2][0],list[3][0]

I want to implement a sort so that it sorts through the second value of every list, so e.g. list[0][1],list[1][1],list[2][1],list[3][1]

This is my list:

[[130, 266.07], [46, 174.14], [169, 187.01], [179, 488.69], [53, 401.53], [128, 106.88], [97, 398.33], [152, 493.87], [20, 205.43], [94, 248.14]]

When sorted it will be like this:

[[20, 205.43], [46, 174.14], [53, 401.53], [94, 248.14], [97, 398.33], [128, 106.88], [130, 266.07], [152, 493.87], [169, 187.01], [179, 488.69]]

I want it to sort the second value of the list. How should i change my code to accomplish this? Any help is appreciated.

This is my sorting algorithm:

def swapElements(myList,i,j):
   temp = myList[i]
   myList[i] = myList[j]
   myList[j] = temp

def getMinIndex(list,start,stop):

        minIndex = start
        for j in range(start,stop):
            if list[j]<list[minIndex]:
                minIndex = j

        return minIndex

def selectionSort(list):

    for i in range(len(list)):

        minIndex = getMinIndex(list,i,len(list))

        swapElements(list, i, minIndex)
    print(list)

def SelectionSortPrice(list):
    selectionSort(list)
  #printList(list) ##part of a different function to format the list, irrelevant

SelectionSortPrice(x)

Upvotes: 0

Views: 305

Answers (1)

cosmic_inquiry
cosmic_inquiry

Reputation: 2684

sorted(yourlist, key= lambda num: num[1])

Upvotes: 1

Related Questions