[Tutor] Sorting a list manually

Alan Gauld alan.gauld at yahoo.co.uk
Thu Aug 12 04:49:21 EDT 2021


On 12/08/2021 08:23, nzbz xx wrote:
> 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:

> 12
> 
> However, when I tested the code using a different list e.g. [1, 2, 3, 4],
> the output is:
> 12
> 
> The output should only have a total of 4 steps. What's wrong with my code?

What makes you think it should only have 4 steps?
What part of your code makes it stop after 4 steps?
You always complete both loops so 4x3=12 steps regardless of input.

Hint:
To do it in less you would need to detect when the list was sorted.
One way to do so would be to mark whether the list was changed during
the inner loop. If there were no changes then break out of the outer loop.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list