[Tutor] Sorting a list manually
nzbz xx
nzbzxx at gmail.com
Thu Aug 12 03:23:40 EDT 2021
I am trying to create a def function where I can sort a list in ascending
order by starting with the first item in the list and comparing it to the
number next to it. The evolution of the list [4, 3, 2, 1] would look as
such:
[*4*, 3, 2, 1] [3, *4*, 2, 1] [3, 2, *4*, 1] [3, 2, 1, *4*]
[*3*, 2, 1, 4] [2, *3*, 1, 4] [2, 1, *3*, 4] [2, 1, 3, *4*]
[*2*, 1, 3, 4] [1, *2*, 3, 4] [1, 2, *3*, 4] [1, 2, 3, *4*]
[*1*, 2, 3, 4] [1, *2*, 3, 4] [1, 2, *3*, 4] [1, 2, 3, *4*]
There's a total of 12 steps in the sorting above. So far, I've managed to
solve the same list using the code below:
def sorting_function(k):
steps_count = 0
for j in range(len(k)):
for i in range(len(k)-1):
if k[i] > k[i+1]:
k[i], k[i+1] = k[i+1], k[i]
steps_count = steps_count + 1
print(k)
print(steps_count)
k = [4,3,2,1]
sorting_function(k)
And got the following output:
[3, 4, 2, 1]
[3, 2, 4, 1]
[3, 2, 1, 4]
[2, 3, 1, 4]
[2, 1, 3, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
12
However, when I tested the code using a different list e.g. [1, 2, 3, 4],
the output is:
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
12
The output should only have a total of 4 steps. What's wrong with my code?
More information about the Tutor
mailing list