#๐Ÿ”’ Problem implementing selection sort algorithm

4 messages ยท Page 1 of 1 (latest)

bleak tartan
#

Hello guys, I know there are several issues with my selection sort algorithm; when I try to sort the list, only half of the list is sorted. This is because when I assume that the biggest element is always the first one, this element at one point only remains at a particular position and no swapping take place.

Can someone explain what is wrong in my code, how can I modify it please.


# Selection Sort

def selection_sort():
    # loop to find biggest num
    biggestNum = listOfNum[0]
    length = len(listOfNum)
    swap = True
    while( swap ):
        swap = False
        for num in range(1, length):
            if num == length - 1:
                break
            if listOfNum[num] > biggestNum:
                biggestNum = listOfNum[num]
                temp = listOfNum[length - 1] # last element of list store to temp
                listOfNum[length - 1] = biggestNum # last element holds max value
                listOfNum[num] = temp # swap current index with last index
                swap = True
        biggestNum = listOfNum[0]
        length = length - 1
    print(listOfNum)




listOfNum = [10,9,8,5,100,367,166,69,66,1]
selection_sort()
open forgeBOT
#

@bleak tartan

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

open forgeBOT
#

@bleak tartan

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.