Last active
April 25, 2020 09:18
-
-
Save lydell/0dfdd903fd68cc9a9a48c385f980ef75 to your computer and use it in GitHub Desktop.
A stableSort function that uses plain .sort if stable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 11 and 513 come from here: https://mathiasbynens.be/demo/sort-stability | |
function checkStable(length) { | |
return Array.apply(null, { length: length }) | |
.map(function (_, i) { | |
return i; | |
}) | |
.sort(function () { | |
return 0; | |
}) | |
.every(function (n, i, a) { | |
return i === 0 || a[i - 1] === n - 1; | |
}); | |
} | |
var stable11 = undefined; | |
var stable513 = undefined; | |
function stableSort(a, f) { | |
if (a.length < 11) { | |
a.sort(f); | |
} else if (a.length < 513) { | |
if (stable11 === undefined) { | |
stable11 = checkStable(11); | |
} | |
if (stable11) { | |
a.sort(f); | |
} else { | |
whateverStableSortImplementation(a, f); | |
} | |
} else { | |
if (stable513 === undefined) { | |
stable513 = checkStable(513); | |
} | |
if (stable513) { | |
a.sort(f); | |
} else { | |
whateverStableSortImplementation(a, f); | |
} | |
} | |
} | |
function whateverStableSortImplementation(a, f) {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment