Compare adjacent elements and repeatedly bubble the largest element to the end.
Great for visualizing nested loops and swap-heavy sorting behavior.
function bubbleSort(arr) {
const a = [...arr];
for (let i = 0; i < a.length - 1; i++) {
for (let j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
[a[j], a[j + 1]] = [a[j + 1], a[j]];
}
}
}
return a;
}
const input = [8, 3, 1, 6, 2, 7];
console.log('Sorted:', bubbleSort(input));Divide-and-conquer sorting using a pivot and recursive partitioning.
Useful for recursion + partition visualization in one run.
function quickSort(arr) {
if (arr.length <= 1) return arr;
const pivot = arr[arr.length - 1];
const left = [];
const right = [];
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) left.push(arr[i]);
else right.push(arr[i]);
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
const input = [9, 4, 2, 8, 1, 6, 3];
console.log('Sorted:', quickSort(input));Search in a sorted array by halving the search space each step.
Perfect for understanding loop invariants and midpoint updates.
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
const values = [2, 4, 7, 11, 15, 19, 22, 31];
console.log('Index:', binarySearch(values, 19));