Writing a Bubble-Sorting Algorithm

Flowchart I designed for a bubble sorting algorithm
October 14, 2019 OliverCordingl1 0 Comments

Hi, there! It’s me, Oliver. In this article, I am going to explain the simple yet effective Bubble Sort algorithm, and how you can write your own in Python and C!

What is a Sorting Algorithm?

A Sorting Algorithm is an algorithm that sorts lists of numbers into numerical order. As humans, our brains have figured out how to do this subconsciously, however, to make a computer do it we need to design what is commonly referred to as a sorting algorithm. There are hundreds of sorting algorithms out there, and each one is good for a specific purpose, and of course, has a specific level of complexity attached to it. In my opinion, the “Bubble Sorting” algorithm is the simplest I have seen, and although it may not be the most efficient of sorting algorithms, I have found it is probably the easiest to get your head around how computers and modern programming languages order lists of numbers.

How does it work?

A Bubble Sort algorithm works by cycling through each numerical entry in a list and comparing it to the entry next to it. If the first item is more than the comparing item, then it will swap them over. This is then repeated for every item in the list. Here, let me show you with a gif;

Bubble Sort example.
Gif recorded from VisualGo (Sorting)

I have also designed a basic flowchart here:

Flowchart I designed for a bubble sorting algorithm
Flowchart for a bubble-sorting algorithm

Writing the Code!

Python

So, with the knowledge of how one of these algorithms work, we can begin to start writing our algorithm. Assuming that you have extremely basic Python (or programming in general) knowledge, you should be able to follow along very easily. If you don’t, don’t worry as I will try my best to explain what is going on.

# We start out by creating a function, with our only argument being ‘arr’, which is our numerical array
def bubbleSort(arr):
    # Setting the variables that we need for the program.
    # 'x' and ‘y’ are the temporary values that we will need to store the array values that will be switched
    # ‘cycles’ will count how many times the array has been scanned
    x = y = cycles = 0

    # Repeat the switching process for every item in the array.
    while cycles < len(a):
        # Cycle through every item in the array
        # (except for the final one, as otherwise we will go out of range when scanning for the next number.)
        for i in range(len(a) - 1):
            # Set the temporary variables so we can reorganise
            x = arr[i]
            y = arr[i + 1]

            # Check if the current element in the array is less than or equal to the upcoming element.
            if (x >= y):
                # Swap the elements
                arr[i + 1] = x
                arr[i] = y

            # Increment the cycles by one
            cycles += 1

arrayToSort = [22,5,13,2,7,8,1,10,21]
print(arrayToSort) # -> [22, 5, 13, 2, 7, 8, 1, 10, 21]
bubbleSort(arrayToSort)
print(arrayToSort) # -> [1, 2, 5, 7, 8, 10, 13, 21, 22]
C (/C++ too, I think)

I have to be perfectly honest, I truly suck at C. However, I am trying to learn it and get better at it, so I am trying to use it as much as I can to the best of my ability. (Granted, my ability is subzero, but we don’t talk about that).

If you have any suggestions about what can be better about this, please either leave a comment, email me or Tweet me @OliverCordingl1.

#include <stdio.h>

// The main bubble sort function, takes the array and the array size as arguments.
void bubbleSort(int arr[], int size) {

    // Iterate through each number except the last
    for (int count = 0; count < size - 1; ++count) {
        for (int i = 0; i < size - count - 1; ++i) { // Iterate through each number, missing numbers that have already been sorted

            // Create our temporary variables to reassign the array values
            int tempX = arr[i];
            int tempY = arr[i + 1];

            if (tempX > tempY) { // This can be changed to a '<' if you need to have the list descend.
                // Reorder the two array values if they need to be sorted
                arr[i] = tempY;
                arr[i + 1] = tempX;
            }
        }
    }
}

// Function to print out arrays as there is no native function to do this.
void printArray(int arr[], int size) {
    for (int i = 0; i < size - 1; ++i) {
        printf("%d, ", arr[i]);
    }
    printf("%d\n", arr[size - 1]); // This is a pretty standard function across many C projects, although I modified it to place commas by making the loop one less iteration long and printing the final number at the end.
}

int main() {
    // Create the array to be sorted
    int arr[] = {52, 4, 1, 23, 5, 9, 0, 2, 9, -1};

    // Calculate the size of the array (Slightly confusing, I know, but it seems to be the only answer on the internet.)
    int size = sizeof(arr) / sizeof(int);

    // Print the initial array
    printf("Before Sorting: ");
    printArray(arr, size);

    // Process the array
    bubbleSort(arr, size);

    // Print the bubble-sorted array
    printf("After Sorting: ");
    printArray(arr, size);

    return 0; // Exit program with no errors
}

As you can see by my code commenting, I did do a bit of ‘Googling’ to learn how to print out an array to the terminal and also to calculate the size of the array.

I still can’t quite get my head around how the thing to calculate the array size actually works, however, I am going to do a bit more reading into it.

Anyways, that is the end, so thank you so much for reading if you made it this far! I hope you found this article useful and possibly learned something new!

Leave a Reply:

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