Introduction to Bubble Sort
Bubble sort works by iterating through the array repeatedly, comparing adjacent elements and swapping them if they are in the wrong order.
The algorithm keeps track of the sorted partition of the array and continues sorting the remaining unsorted partition until the entire array is sorted.
This process is repeated until the array is fully sorted. It starts with the first pair of elements and continues until the last pair.
It is named as “bubble sort” because smaller elements “bubble” to the top of the list.
Bubble Sort Demonstration
Let’s say we have an array [5, 2, 8, 3, 1].
In the first iteration, the algorithm compares 5 and 2, swaps them to get [2, 5, 8, 3, 1].
Then it compares 5 and 8, no swap needed. It goes on like this until it reaches the end of the array. After the first iteration, the largest element (8) is in its correct position at the end of the array.
The remaining unsorted partition is [2, 3, 1]. The algorithm continues with the second iteration, again comparing and swapping elements until the array is sorted.
The final sorted array will be [1, 2, 3, 5, 8].
To see bubble sort in action take a look at this Scratch project.
Pros & Cons
Pros and Cons of Bubble Sort
- Simple and easy to understand
- Because it’s an in-place sorting algorithm it requires minimal additional memory space
- Works well for small lists or nearly sorted lists
- Not efficient for large lists
- Time complexity is O(n^2), which means the execution time increases rapidly with the growing size of the array
- Not suitable for real-world applications with large datasets
Python Code for Bubble Sort