Jul-28-2018, 02:51 AM
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] '''