<em>Bad Code</em>

Bubble Sort | <em>Bad Code</em> [3]

What It Does

This is my own version of the simple sorting algorithm bubble sort. The function takes the numbers 1 to 9  in a random order, and re-sorts them into ascending order. The first value is compared with the second value: if the first is greater than the second, their locations in the list are swapped. Then the second and third are compared etc., until the penultimate and ultimate terms have been compared, and swapped if necessary. This process in then repeated i numbers of times, where i is the total number of terms in the list. (A for loop is used to run the program 5 times, to demonstrate that it still works with different randomised lists.)

import random


list = [1,2,3,4,5,6,7,8,9]


def sort(k):
    random.shuffle(list)
    print("Run", k, "- Randomised:", list)
    for i in range(len(list)):
        for j in range(0,len(list)-1):
            if list[j] > list[j+1]:
                temp = list[j+1]
                list[j+1] = list[j]
                list[j] = temp
    print("Run", k, "- Sorted:", list, "\n")


#Main Program
for k in range(5):
    sort(k+1)

 

This algorithm is very reliable, but may unnecessarily continue to sort the list even after all terms are in order. If only the last two terms are out of order, for example, the list will still continue to be sorted after the first iteration of the outer for loop in the function “sort”. A check could be performed after each iteration of this for loop, to see if list[0] < list[1] <list[2] … list[len(list)-1], but of course this would slow down the speed at which the sort can be executed. Maybe there is an ideal frequency at which this check could occur (every time i%2=0, or every i%3=0 perhaps?) that minimises the average time that a random list of 9 numbers can be sorted?

Leave a Reply

Your email address will not be published. Required fields are marked *