In python you need to be able to sort lists right? Well one simple, although inefficient, way to do this is with the bubble sort algorithm. How this works is it compares two elements in the list 1,2 then 2,3, then 3,4 and so on and compares them. If one is bigger than the other it moves up, how this works is it pushes the highest element up and goes through the list over and over until each element has been sorted in the list. This is what the algorithm would look like it code form. Also quick side note the reason for the use of the swapped variable is it starts the while loop off, however immediately sets the variable to false, if the elements needs to be swapped based on that if statement it sets it back to true so the loop can continue. If there are no elements to be swapped then the condition remains false, otherwise the loop would run forever.
Code:
list = [3, 4, 1, 2, 5]
swapped = true
for i in range(len(list) -1): #Number of swaps necessary for the algorithm, total elements minus one
swapped = false
if list[i] > list[i + 1]:
list[i], list[i + 1] = list[i + 1], list[i]
swapped = true #Marks that element as swapped
print(list)
Result:
[1, 2, 3, 4, 5]
Now some python enthusiasts might be thinking “Wait a minute isn’t there a method that does this for you, and you would be right in thinking so it looks just like this.
Code:
list = [2, 3, 4, 5, 1]
list.sort()
print(list)
list.reverse()
print(list)
Result:
[1, 2, 3, 4, 5)
[5, 4, 3, 2, 1]
As you can clearly see this is a lot less code and far more efficient but this was a little taste of algorithms in python.