Bubble Sort in Python

Bubble Sort in Python

ECX 30 Days of Code and Design

Day 24

Bubble Sort

Task

Bubble sort is a basic algorithm for sorting (rearranging in ascending or descending order) elements in a list. It operates as follows:

  • Iterate across a list, element by element
  • Upon encountering any two adjacent elements which are in the "wrong" designated order (ascending or descending), swap their positions in the list, else do nothing
  • Do this until your iteration reaches the end of the list
  • Repeat steps 1 through 3 until there are no longer any adjacent elements in the "wrong" order, then stop

(See more: Bubble sort).

Write a function that takes in two parameters, a list of alphabets, and a flag designating what order in which to sort. Using the Bubble sort algorithm, have this function return a sorted version of the input list.

E.g.: f(['x', 'c', 'b', 'v', 'z', 'a'], "ascending") => ['a', 'b', 'c', 'v', 'x', 'z' ]

Note: Type checking (or Exception Handling) is necessary. Disregard case-sensitivity.

My Approach

This is the full code. It would be explained in bits throughout this article.

def bubble_sort(list_items, order):
    """Sorts a list using Bubble sort"""

    size_of_list = len(list_items)
    for j in range(size_of_list - 1):
        for i in range(size_of_list - 1):

            # Ascending order
            if order == 'a' or order == 'A':
                if list_items[i].lower() > list_items[i + 1].lower():
                    temp = list_items[i + 1]
                    list_items[i + 1] = list_items[i]
                    list_items[i] = temp

            # Descending order
            elif order == 'd' or order == 'D':
                if list_items[i + 1].lower() > list_items[i].lower():
                    temp = list_items[i]
                    list_items[i] = list_items[i + 1]
                    list_items[i + 1] = temp

            else:
                return print("Invalid order! Enter either 'a' or 'd'")

    return print(list_items)


# Order has two choices; [a]scending or [d]escending order.
list_item = ['v', 'e', 'r', 't', 'i', 'c', 'a', 'l']

# Function call
bubble_sort(list_item, 'a')             
bubble_sort(list_item, 'd')             
bubble_sort(list_item, 'z')

First, we define the function, bubble_sort(), which takes two parameters, a list and the order of sorting. Next, we find the number of list items in the given list using the len() function.

def bubble_sort(list_items, order):
    """Sorts a list using Bubble sort"""

    size_of_list = len(list_items)

Next, we make use of two for loops for the sorting. If the length of the list is 7, we would sort the list 6 × 6 = 36 times to ensure that the list is fully sorted to the given order.

    for j in range(size_of_list - 1):
        for i in range(size_of_list - 1):

If ascending order is chosen, a list item is checked against the next item, if the item is bigger than the next item it exchanges place with it, else it stays in place, and the next item is checked against the one next to it. This continues until we get to the second to the last list item; after which we start from the beginning until size_of_list - 1.

            # Ascending order
            if order == 'a' or order == 'A':
                if list_items[i].lower() > list_items[i + 1].lower():
                    temp = list_items[i + 1]
                    list_items[i + 1] = list_items[i]
                    list_items[i] = temp

If descending order is chosen, a list item is checked against the next item, if it is smaller than the next item, it exchanges place with it, else it stays in place, and the next item is checked against the one next to it. This continues until we get to the second to the last list item; after which we start from the beginning until size_of_list - 1.

            # Descending order
            elif order == 'd' or order == 'D':
                if list_items[i + 1].lower() > list_items[i].lower():
                    temp = list_items[i]
                    list_items[i] = list_items[i + 1]
                    list_items[i + 1] = temp

If a wrong order; that is, neither ascending nor descending order is chosen, we print an error to the screen.

            else:
                return print("Invalid order! Enter either 'a' or 'd'")

After the sorting, the sorted list is printed out.

    return print(list_items)

Finally, we create an order list and pass it to a function. We would check the list arrangement, when ascending, descending, and when a wrong order is chosen.

list_item = ['v', 'e', 'r', 't', 'i', 'c', 'a', 'l']

bubble_sort(list_item, 'a')         
bubble_sort(list_item, 'd')           
bubble_sort(list_item, 'z')

Output

['a', 'c', 'e', 'i', 'l', 'r', 't', 'v']
['v', 't', 'r', 'l', 'i', 'e', 'c', 'a']
Invalid order! Enter either 'a' or 'd'

Run the code on Repit.