In this article, you’ll learn about the working of the Bubble Sort algorithm, the pseudocode of the Bubble Sort algorithm, its time and space complexity, and its implementation in various programming languages like C++, Python, C, and JavaScript.
How Does the Bubble Sort Algorithm Work?
Bubble Sort is the simplest sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they’re in the wrong order. This concept can be explained more efficiently with the help of an example. Consider an unsorted array with the following elements: {16, 12, 15, 13, 19}.
Example:
Here the adjacent elements are compared and if they’re not in ascending order, they’re swapped.
Pseudocode of the Bubble Sort Algorithm
In pseudocode, the Bubble Sort algorithm can be expressed as:
The above algorithm processes all the comparisons even if the array is already sorted. It can be optimized further by stopping the algorithm if the inner loop didn’t cause any swap. This will reduce the execution time of the algorithm.
Thus, the pseudocode of the optimized Bubble Sort algorithm can be expressed as:
Time Complexity and Auxiliary Space of the Bubble Sort Algorithm
The worst-case time complexity of the Bubble Sort Algorithm is O(n^2). It occurs when the array is in descending order and you want to sort it in ascending order or vice-versa.
The best-case time complexity of the Bubble Sort Algorithm is O(n). It occurs when the array is already sorted.
The average-case time complexity of the Bubble Sort Algorithm is O(n^2). It occurs when the elements of the array are in jumbled order.
The auxiliary space required for the Bubble Sort algorithm is O(1).
C++ Implementation of the Bubble Sort Algorithm
Below is the C++ implementation of the Bubble Sort algorithm:
Output:
Python Implementation of the Bubble Sort Algorithm
Below is the Python implementation of the Bubble Sort algorithm:
Output:
C Implementation of the Bubble Sort Algorithm
Below is the C implementation of the Bubble Sort algorithm:
Output:
JavaScript Implementation of the Bubble Sort Algorithm
Below is the JavaScript implementation of the Bubble Sort algorithm:
Output:
Now You Understand the Working of the Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm and is mainly used to understand the foundations of sorting. Bubble Sort can also be implemented recursively, but it provides no additional advantages to do so.
Using Python, you can implement the Bubble Sort algorithm with ease. If you’re unfamiliar with Python and want to kickstart your journey, starting off with a “Hello World” script is a great choice.