Bubble Sort
ℹ️ Sorting algorithm that compares every adjacent pair of values and swaps their position if the first value is greater than another. Complexity O(n²)
Description
The bubble sort algorithm runs in O(n²) time, making it an inefficient algorithm for a larger list.
The idea behind the bubble sort is that every adjacent pair of values is repeatedly compared, and then these values swap their positions if the first value is greater than the second value. This way during each pass through the array, the largest value “bubbles up” to the top.
Example
Let's imagine that we need to sort the following array using bubble sorting: [7, 1, 4, 3, 8]
. Here is the list of the steps that bubble sorting will do to sort this array:
[7, 1, 4, 3, 8] -> [1, 7, 4, 3, 8]
[1, 7, 4, 3, 8] -> [1, 4, 7, 3, 8]
[1, 4, 7, 3, 8] -> [1, 4, 3, 7, 8]
[1, 4, 3, 7, 8] -> [1, 4, 3, 7, 8]
Second pass:
[1, 4, 3, 7, 8] -> [1, 4, 3, 7, 8]
[1, 4, 3, 7, 8] -> [1, 3, 4, 7, 8]
[1, 3, 4, 7, 8] -> [1, 3, 4, 7, 8]
[1, 3, 4, 7, 8] -> [1, 3, 4, 7, 8]
Now, our array is already sorted, but the algorithm doesn't know about it. The algorithm still needs one whole pass to end its sorting.
Third pass:
[1, 4, 3, 7, 8] -> [1, 4, 3, 7, 8]
[1, 3, 4, 7, 8] -> [1, 3, 4, 7, 8]
[1, 3, 4, 7, 8] -> [1, 3, 4, 7, 8]
[1, 3, 4, 7, 8] -> [1, 3, 4, 7, 8]
Code implementation
Here is one of the possible ways to implement bubble sorting:
Even if an array is sorted the function always runs O(n²) time. It can be optimized if the inner loop didn't make any swap during its execution.
This time if our inputArr
is already sorted complexity will be O(n).
Complexity
Worst and Avg. Time Complexity: O(n²)
Best Case Time Complexity: O(n). Happens only when an array is already sorted.
Last updated