The heavy lifting is done by the .sort()
method which uses an optimized algorithm (search ‘merge sort’, among other algos) that relies on the callback function to return the difference between a
and b
, which values are supplied by the method, iteratively. The algorithm is what selects a and b on each iteration. I could be wrong, but that only means the flipside is correct. Will need to examine this to overcome my memory deficiency: When the callback returns a negative value, the values referred by a and b are swapped, in-place.
To read up on a bubble sort algorithm, visit this thread:
That is not anywhere close to the algorithm that JS uses, but illustrates iteration, comparison and swapping (rather old school).
const bubbleSort = function (obj) {
const f = function (n) {
let a = [];
let i = 0;
while (a.length < n) {
a.push(n - i++);
}
return a;
}
let r = f(obj.length)
for (let i = 0; i < obj.length; i++) {
r.pop();
for (let j of r) {
[a, b] = [obj[i], obj[j]]
if (a > b) {
[obj[i], obj[j]] = [obj[j], obj[i]]
}
}
}
return obj;
}
> bubbleSort('threeblindmice'.split(''))
<- (14) ['b', 'c', 'd', 'e', 'e', 'e', 'h', 'i', 'l', 'i', 'm', 'n', 'r', 't']
> bubbleSort([20, 26, 46, 14, 57, 11, 75, 31, 4, 51, 88, 1, 77, 20, 46, 25, 18, 98, 35, 45])
<- (20) [1, 4, 11, 14, 20, 18, 20, 26, 25, 31, 45, 35, 46, 46, 51, 57, 75, 88, 77, 98]