Manually sort a list of 10 integers in python

Kordan9090 picture Kordan9090 · Feb 16, 2014 · Viewed 15.2k times · Source

I'm fairly new to programming; I've only been studying Python for a few weeks. I've been given an exercise recently that asks me to generate a list of integers, and then manually sort the numbers from lowest to highest in a separate list.

import random
unordered = list(range(10))
ordered = []
lowest = 0
i = 0

random.shuffle(unordered)

lowest = unordered[0]

while i in unordered:
    if  unordered[i] < lowest:
        lowest = unordered[i]
        i += 1
    if i >= len(unordered):
        i = 0

ordered.append(lowest)
unordered.remove(lowest)
lowest = unordered[i]

print(ordered)

This is what I have so far, and to be quite frank, it doesn't work at all. The pseudocode I have been given is this:

  • Create an empty list to hold the ordered elements
  • While there are still elements in the unordered list
    • Set a variable, lowest, to the first element in the unordered list
    • For each element in the unordered list
      • If the element is lower than lowest
      • Assign the value of that element to lowest
    • Append lowest to the ordered list
    • Remove lowest from the unordered list
  • Print out the ordered list

The biggest issue I'm having so far is that my counter doesn't reliably give me a way to pick out the lowest number from my list unordered. And then I'm having issues with indexing my list i.e. the index being out of range. Can anyone give me a bit of feedback on where I'm going wrong?

Also, I was given this info which I'm not really sure about:

You can use an established method to sort the list called the Selection Sort.

I'm not supposed to be using Python's built in sort methods this time around. It's all supposed to be done manually. Thanks for any help!

Answer

Ty Hitzeman picture Ty Hitzeman · Apr 10, 2019

You can do this without having to create another list.

x = [5, 4, 3, 2, 5, 1]
n = len(x)

# Traverse through all list elements
for i in range(n):

# Traverse the list from 0 to n-i-1
# (The last element will already be in place after first pass, so no need to re-check)
for j in range(0, n-i-1):

    # Swap if current element is greater than next
    if x[j] > x[j+1]:
        x[j], x[j+1] = x[j+1], x[j]
print(x)

This works with duplicates and descending lists. It also includes a minor optimization to avoid an unnecessary comparison on the last element.

Note: this answer and all the others use bubble sort, which is simple but inefficient. If you're looking for performance, you're much better off with another sorting algorithm. See which is best sorting algorithm and why?