Home > Software design >  How does this sorting code work? How does it find the minimum numbers?
How does this sorting code work? How does it find the minimum numbers?

Time:05-11

I found this code on stack overflow answering a topic I was working on (how to sort a list of integers without using sort and sorted built-in functions):

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list = []

while data_list:
    minimum = data_list[0]  # arbitrary number in list
    for x in data_list:
        if x < minimum:
            minimum = x
    new_list.append(minimum)
    data_list.remove(minimum)

print(new_list)

It works perfectly well. But when I go through it I get confused on how it works.

minimum is set to the first element in the list, -5. When the for loop kicks in it starts with the first element of the list. x is thereby equal to -5, and so x is not less than minimum. How can the iteration go on, then?

CodePudding user response:

I hope some step-by-step visualization will help you: https://pythontutor.com/visualize.html#code=data_list = [-5, -23, 5, 0, 23, -6, 23, 67] new_list = [] while data_list: minimum = data_list[0] # arbitrary number in list for x in data_list: if x < minimum: minimum = x new_list.append(minimum) data_list.remove(minimum) print(new_list)&cumulative=false&curInstr=43&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=[]&textReferences=false

I already put your code inside, however, it's not an optimal way to make a sort implementation. You can check the following algorithms: quicksort, merge sort, bubble sort... etc.

The general explanation of different sorting algorithms: https://www.programiz.com/dsa/sorting-algorithm

Also there you can find algorithms in general, with their implementation to visualize them in pythontutor step-by-step :) https://www.techiedelight.com/top-25-algorithms-every-programmer-should-know/

I know it's a lot, but I hope it's gonna help you somehow :D

CodePudding user response:

The code works by finding the minimum of data_list, removing it from data_list and appending it to new_list. So it stores numbers in new_list from least to greatest.

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list = []

while data_list:
    minimum = data_list[0]  # get default number as a placeholder, minimum does not store minimum yet
    for x in data_list:
        if x < minimum: # if it finds a new minimum
            minimum = x # then minimum is set to that
    #since it checked all values of data_list, now, minimum is definitely the minimum
    new_list.append(minimum) # new_list has the minimum added
    data_list.remove(minimum) # the number is now in the correct position, so it can be discarded.

print(new_list)
  • Related