Python Forum
Unexpected Results for Selection Sort
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unexpected Results for Selection Sort
#1
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]
'''
Reply
#2
In line 10: minIndex = i instead of minIndex = 1
Reply
#3
Thank you so much for taking the time. I am grateful.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  sort search results by similarity of characters jacksfrustration 5 446 Feb-16-2024, 11:59 PM
Last Post: deanhystad
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,325 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,397 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Search Results Web results Printing the number of days in a given month and year afefDXCTN 1 2,244 Aug-21-2020, 12:20 PM
Last Post: DeaD_EyE
  Sort by the largest number of the same results (frequency) inlovewiththedj 3 2,222 Apr-01-2020, 07:29 AM
Last Post: DPaul
  How to append one function1 results to function2 results SriRajesh 5 3,175 Jan-02-2020, 12:11 PM
Last Post: Killertjuh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020