Sort an array in place with adjacent swaps and a comparator
Implement bubbleSort(array, compare?), an in-place bubble sort. Each pass walks the array from left to right, compares every pair of neighbours, and swaps them when they are out of order. The largest remaining element “bubbles” to the end of the unsorted part on every pass.
bubbleSort(array, compare?) // => array (the same reference, now sorted)
compare(left, right) returns a number. A positive result means left must come after right, so swap them. Zero or a negative result means leave them.compare with the left neighbour first and the right neighbour second, and only with elements of the array.compare, order values with the < and > operators. Unlike the default of Array.prototype.sort, numbers sort numerically: [10, 9, 100] becomes [9, 10, 100].n uses exactly n - 1 comparisons.n uses more than n * (n - 1) / 2 comparisons.0 or 1 use no comparisons.bubbleSort([5, -2, 9, 0, 5]);
// => [-2, 0, 5, 5, 9]
bubbleSort([10, 9, 100, 1]);
// => [1, 9, 10, 100]
bubbleSort(['pear', 'fig', 'apple']);
// => ['apple', 'fig', 'pear']
const tasks = [
{ title: 'Deploy', priority: 2 },
{ title: 'Fix bug', priority: 1 },
{ title: 'Review', priority: 2 },
];
bubbleSort(tasks, (a, b) => a.priority - b.priority);
// => Fix bug, Deploy, Review (Deploy stays before Review)
bubbleSort([3, 1, 2], (a, b) => b - a);
// => [3, 2, 1]
Do not use Array.prototype.sort or Array.prototype.toSorted.