Search code examples
pythonselection-sort

Selection Sort Issue: Why is the biggest element of the list put at the front of the list?


I've been practicing SELECTION SORT using Python 3 with a list of lists I read from a file. I'm trying to print the list in increasing order of the first element of each inner list (List[i][0]).

This is my list: [[130.0, 266.07], [46.0, 174.14], [169.0, 187.01], [179.0, 488.69], [53.0, 401.53], [128.0, 106.88], [97.0, 398.33], [152.0, 493.87], [20.0, 205.43], [94.0, 248.14]]

However, with this code:

def swapElements(aList, a, b):
    temp = aList[a]
    aList[a] = aList[b]
    aList[b] = temp

def selection_sort(aList):
    for i in range(0, len(aList)):
        minimum = 0
        for j in range(i, len(aList)):
            if aList[j][0] < aList[minimum][0]:
                minimum = j
        if minimum != i:
            swapElements(aList, i, minimum)
    print(aList)

the output always puts the biggest element of the list at the start:

[[179.0, 488.69], [20.0, 205.43], [46.0, 174.14], [53.0, 401.53], [94.0, 248.14], [97.0, 398.33], [128.0, 106.88], [130.0, 266.07], [152.0, 493.87], [169.0, 187.01]]

Can anyone please explain why and show where my code is wrong?


Solution

  • you ranges are slightly off. compare with the wikipedia article. the altorithm there in your notation:

    def swapElements(lst, a, b):
        lst[a], lst[b] = lst[b], lst[a]
    
    def selection_sort(aList):
        for i in range(len(aList)-1):         # -1 is vital!
            minimum = i                       # the minimum index starts at i; not 0
            for j in range(i+1, len(aList)):  # here it's the +1
                if aList[j][0] < aList[minimum][0]:
                    minimum = j
            if minimum != i:
                swapElements(aList, i, minimum)
        print(aList)
    

    and as i mentioned in the comment: python can swap values simply like this: lst[a], lst[b] = lst[b], lst[a].