Skip to content

Sort without `sort()`

Sorting questions test whether you can turn an ordering rule into comparisons and explain the cost. These examples sort numbers without calling JavaScript’s built-in sort().

Bubble sort compares neighboring values and swaps them when they are out of order. Each pass moves a large (or, for descending order, small) value toward the end.

function bubbleSort(values, direction = 'asc') {
const result = [...values];
const comesBefore = direction === 'desc'
? (left, right) => left < right
: (left, right) => left > right;
for (let end = result.length - 1; end > 0; end--) {
let swapped = false;
for (let index = 0; index < end; index++) {
if (comesBefore(result[index], result[index + 1])) {
[result[index], result[index + 1]] = [result[index + 1], result[index]];
swapped = true;
}
}
if (!swapped) break;
}
return result;
}
const numbers = [4, 2, 1, 2, -7, 18, 9];
console.log(bubbleSort(numbers)); // [-7, 1, 2, 2, 4, 9, 18]
console.log(bubbleSort(numbers, 'desc')); // [18, 9, 4, 2, 2, 1, -7]
console.log(numbers); // original array is unchanged

The copy keeps the input unchanged. Bubble sort takes O(n²) time in the average and worst cases and O(n) extra space here because of that copy (or O(1) extra space if sorting the original array in place). An already sorted input can finish in O(n) time because of the swapped check.

Merge sort splits the array until each piece has one value, then merges sorted pieces. The same comparison rule supports ascending and descending order.

function mergeSort(values, direction = 'asc') {
if (values.length <= 1) return [...values];
const middle = Math.floor(values.length / 2);
const left = mergeSort(values.slice(0, middle), direction);
const right = mergeSort(values.slice(middle), direction);
return merge(left, right, direction);
}
function merge(left, right, direction) {
const result = [];
const leftFirst = direction === 'desc'
? (a, b) => a >= b
: (a, b) => a <= b;
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
if (leftFirst(left[i], right[j])) result.push(left[i++]);
else result.push(right[j++]);
}
return result.concat(left.slice(i), right.slice(j));
}
console.log(mergeSort([4, 2, 1, 2, -7, 18, 9]));
// [-7, 1, 2, 2, 4, 9, 18]
console.log(mergeSort([4, 2, 1, 2, -7, 18, 9], 'desc'));
// [18, 9, 4, 2, 2, 1, -7]

For n values, merge sort takes O(n log n) time. This straightforward version uses O(n) auxiliary space for the merged arrays, plus the recursion stack. It returns a new array.

Bubble sort is useful for learning comparisons, loops, and swaps. Merge sort scales better for large inputs. In production code, use sort() with a comparator unless the exercise specifically asks you to implement an algorithm; JavaScript’s default sort compares values as strings.

const ascending = [...numbers].sort((a, b) => a - b);
const descending = [...numbers].sort((a, b) => b - a);