# [Tutor] I'm having a small problem with my code

Alan Gauld alan.gauld at yahoo.co.uk
Thu May 23 19:58:57 EDT 2019

```On 23/05/2019 13:16, David Lifschitz wrote:

> The next job of the code is to sort the list of numbers that were inputted
> in an ascending fashion.

You are aware that Python lists have a built in sort method?
It will be more efficient than anything you can create
yourself in Python. Assuming you know that and decided
to write a sort routine for fun....

> There is no error from the code, however, when I run the code the first
> inputted number stays in its place and doesn't get sorted with the rest of
> the numbers.

Yes, see below:

> emptyList = []

This is a terrible name since it becomes misleading the
instant you put anything into it!

number_list or similar would be more accurate.
Or even just 'data'....

> nOFN = int(input("how many numbers do you want to sort: "))
>
> for x in range(nOFN):
>     number1 = int(input("input number: "))
>     emptyList.append(number1)

You could have used a list comprehension:

emptyList = [int(input("input number: ")) for n in range(nOFN)]

Now onto the problem sort code

> firstElement = emptyList[0]

Why did you do this? You never refer to firstElement again...

> n = len(emptyList)
> for j in range(1, n):
>     if emptyList[j-1] > emptyList[j]:
>         (emptyList[j-1], emptyList[j]) = (emptyList[j], emptyList[j-1])

Consider the first case, j=1

If the first element is greater than the second
you swap them. Otherwise you leave them in place.

The loop now considers elements 2 and 3.
If 2 >3 you reverse them, otherwise move on.
But if element 3 is less than element 1 you never
go back to move it to the top.

Consider this example - [3,2,1]

1st iteration   -> 2,3,1
2nd iteration   -> 2,1,3

Loop ends.
But you never swapped 1 and 2 after(or during) the last iteration.

Your sort routine is fundamentally flawed. You need a rethink.
But not too much because the built in sort will nearly always be preferred!

Incidentally, creating working sort algorithms is one of the
hardest things to get right in computing. It is one of
those things that can seem right then one specific pattern
will break it.

--
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

```