Python Forum
Unexpected Results for Selection Sort - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Unexpected Results for Selection Sort (/thread-11844.html)



Unexpected Results for Selection Sort - emerger - Jul-28-2018

My book, "Fundamentals of Python, Data Structures" gives me this code for selection sort. I tried the code and got unexpected results (below). I've looked the code over and over and have not copied it wrong. Can anyone help me get a proper sort and/or explain why my code isn't giving me the sorted results (line 30 in the output below)? V/r. Pete
def swap(lyst, i, j):
    temp = lyst[i]
    lyst[i] = lyst[j]
    lyst[j] = temp
    
lyst = [5,3,7,6,9,8,4,2,1]
def selectionSort(lyst):
    i = 0
    while i < len(lyst) -1:
        minIndex = 1
        j = i + 1
        while j < len(lyst):
            if lyst[j] < lyst[minIndex]:
                minIndex = j
            j += 1
        if minIndex != i:
            swap(lyst, minIndex, i)
        i += 1
        print(lyst)
selectionSort(lyst)
'''
output:
[1, 3, 7, 6, 9, 8, 4, 2, 5]
[1, 2, 7, 6, 9, 8, 4, 3, 5]
[1, 7, 2, 6, 9, 8, 4, 3, 5]
[1, 7, 2, 3, 9, 8, 4, 6, 5]
[1, 7, 2, 3, 4, 8, 9, 6, 5]
[1, 7, 2, 3, 4, 5, 9, 6, 8]
[1, 7, 2, 3, 4, 5, 6, 9, 8]
[1, 9, 2, 3, 4, 5, 6, 7, 8]
'''



RE: Unexpected Results for Selection Sort - Nitprog - Jul-28-2018

In line 10: minIndex = i instead of minIndex = 1


RE: Unexpected Results for Selection Sort - emerger - Jul-28-2018

Thank you so much for taking the time. I am grateful.