DSAintermediate 9 min
Put items in order, starting with bubble sort and a visual trace of every swap.
How bubble sort works, why it is O(n squared), and what faster sorts do differently.
Sorted data is much easier to search, compare and display. Sorting is also one of the best places to learn how to reason about algorithms.
Bubble sort repeatedly walks through the list and swaps neighbours that are in the wrong order. After each full pass, the biggest unsorted value has "bubbled" to the right end.
It is simple but slow: up to n passes over n items is O(n squared).
Faster sorts, such as merge sort and quick sort, use a divide-and-conquer approach and reach O(n log n). That is what Array.prototype.sort uses in practice.
Start: we will bubble the biggest value to the right, one pass at a time.
5 and 2. Out of order, so swap.5 and 9. Fine, no swap. Compare 9 and 1: swap. Compare 9 and 6: swap.9 in its final place at the right edge.[ 1, 2, 5, 6, 9 ].Try insertion sort too, which builds the sorted group one item at a time:
Start: the first value is a sorted group of one.
Add a counter for how many swaps happen, and compare a sorted input with a reversed one.
sort() in JavaScript: it compares as text. Use arr.sort((a, b) => a - b).a[j + 1].sort a compare function for numbers.Next: binary search, which needs sorted data.
function bubbleSort(arr) {
const a = [...arr];
for (let end = a.length - 1; end > 0; end--) {
for (let j = 0; j < end; j++) {
if (a[j] > a[j + 1]) {
const tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
}
return a;
}
console.log(bubbleSort([5, 2, 9, 1, 6]));