Search code examples
python-3.xselection-sort

What is wrong with my Selection Sort code?


My code is as follows:

def selection_Sort(aList):
    i = 0
    for j in range(1, len(aList)-1):
        while aList[j] < aList[i]:
            aList[i], aList[j] = aList[j], aList[i]
            i += 1
    return aList

aList = [5,2,3,7,6]

print(selection_Sort(aList))

However, it prints this: [2, 3, 5, 7, 6]

There's probably something wrong with my range but I just can't figure out what. Help? Thanks!


Solution

  • It has nothing to do with your range; that is not a selection sort.

    Try tracing through your algorithm with a paper and pencil to see what is happening.

    A selection sort should have two counting loops: the outer for i and the inner for j. i loops through all but the last element. j loops to find the smallest element in (i,j].

    Hope this helps.