'How does this sorting code work? How does it find the minimum numbers?
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?
Solution 1:[1]
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)
Solution 2:[2]
Perhaps some step-by-step visualization will help you. 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.
Programiz has a general explanation of different sorting algorithms.
Also there you can find algorithms in general, with their implementation to visualize them in pythontutor step-by-step.
I know it's a lot, but I hope it's gonna help you some how.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kenntnisse |
Solution 2 | John Kugelman |