Bubble_Sort
Bubble_Sort
Algorithm:
Below is the algorithm of the bubble sort:
1. Assign a variable of Boolean data type (let’s call it sorted) and let it have a starting value of false.
2. While the array isn’t sorted (!sorted), iterate through elements of array.
3. Compare the first and second elements (adjacent elements in array), if second element is less than first
element, swap the two elements.
4. Do this to the next element in iteration until it reached the end of the array.
5. If we found elements that need to be swapped, sorted variable will always be false, hence continuing
the loop from the start.
6. Once we can’t find elements that need swapping, the sorted will become true, then it will exit the loop.
// Assume the array is sorted first, but it will change it's value to
false if we found unsorted elements in array
sorted = true;
Pro’s
• Bubble sort only takes a few lines of code; hence it is easier to write.
• There is little memory overhead as the data is sorted in place. Once sorted, the data is in memory, ready
for processing.
Con’s
• Bubble sort has a space complexity of O (1), so it is slow. It is slower than selection sort. It will take
amount of time to sort and array.
• It is very not ideal for large array; due to the time it takes to sort an array. Other fast sorting algorithms
such as merge sort and quicksort are ideal for arrays with larger data.
Sources:
• https://www.programiz.com/dsa/bubble-
sort#:~:text=Bubble%20sort%20is%20a%20sorting,is%20called%20a%20bubble%20sort.
• https://www.techwalla.com/articles/advantages-disadvantages-of-bubble-sort