JavaScriptMedium
Sort an array (Bubble Sort)
Bubble sort repeatedly walks through the array swapping adjacent elements that are out of order, so the largest remaining value "bubbles" to the end on each pass; it is O(n²) and mainly a teaching example, but an early-exit flag makes it O(n) for already sorted input.
Algorithm
- For each pass
ifrom 0 ton - 1: - Compare
arr[j]witharr[j + 1]forjfrom 0 ton - i - 2(the lastielements are already in place). - Swap them if they are in the wrong order.
- If a pass makes no swaps, the array is sorted: stop early.
Properties
- Time: O(n²) average and worst case; O(n) best case with the early exit.
- Space: O(1), in place.
- Stable: equal elements keep their relative order (because you only swap when strictly greater).
Why you would not use it in production
Array.prototype.sort (TimSort in V8) is O(n log n), stable, and heavily optimised. Use arr.toSorted((a, b) => a - b) in real code.
What interviewers look for
- Correct loop bounds and the shrinking inner range.
- The early-exit optimisation.
- Mentioning complexity and stability.
- Knowing better algorithms: merge sort (O(n log n), stable), quicksort (O(n log n) average, in place), insertion sort (great for small or nearly sorted arrays, used inside TimSort).
- Not mutating the caller's array unless asked (copy first).
Code example
js
1function bubbleSort(input, compare = (a, b) => a - b) {2 const arr = [...input]; // don't mutate the caller's array3 for (let i = 0; i < arr.length - 1; i++) {4 let swapped = false;5 for (let j = 0; j < arr.length - 1 - i; j++) {6 if (compare(arr[j], arr[j + 1]) > 0) {7 [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];8 swapped = true;9 }10 }11 if (!swapped) break; // already sorted: stop early12 }13 return arr;14}1516console.log(bubbleSort([5, 2, 9, 1, 5, 6])); // [1, 2, 5, 5, 6, 9]17console.log(bubbleSort(["pear", "apple", "fig"], (a, b) => a.localeCompare(b))); // ["apple", "fig", "pear"]1819// Stable: equal keys keep their original order20const people = [{ n: "A", age: 30 }, { n: "B", age: 25 }, { n: "C", age: 30 }];21console.log(bubbleSort(people, (a, b) => a.age - b.age).map((p) => p.n)); // ["B", "A", "C"]2223// Merge sort for comparison: O(n log n), also stable24function mergeSort(arr) {25 if (arr.length <= 1) return arr;26 const mid = arr.length >> 1;27 const [left, right] = [mergeSort(arr.slice(0, mid)), mergeSort(arr.slice(mid))];28 const out = [];29 let i = 0, j = 0;30 while (i < left.length && j < right.length) out.push(left[i] <= right[j] ? left[i++] : right[j++]);31 return [...out, ...left.slice(i), ...right.slice(j)];32}3334const big = Array.from({ length: 3000 }, () => Math.floor(Math.random() * 1e6));35let t = performance.now();36bubbleSort(big);37const bubbleMs = performance.now() - t;38t = performance.now();39const merged = mergeSort(big);40const mergeMs = performance.now() - t;41console.log(`merge sort faster: ${mergeMs < bubbleMs}`, merged.join() === big.toSorted((a, b) => a - b).join()); // merge sort faster: true true
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.