Skip to content

Instantly share code, notes, and snippets.

@gaogao-9
Last active July 2, 2016 22:35
Show Gist options
  • Save gaogao-9/1cf7ab5bdf290c987b04dff22ebed8fc to your computer and use it in GitHub Desktop.
Save gaogao-9/1cf7ab5bdf290c987b04dff22ebed8fc to your computer and use it in GitHub Desktop.
多分これが一番早いと思います。-0と+0の安定ソートは出来ません。
function stableSort(arr, callback){
var indexMap = new Map(null);
for(var i=0;i<arr.length;i++){
indexMap.set(arr[i], i);
}
var result;
arr.sort(function compare(a, b){
result = (callback) ? callback(a, b) : false;
if(result) return result;
return indexMap.get(a) - indexMap.get(b);
});
return arr;
}
console.log([11,10,9,8,7,6,5,4,3,2,1,0].sort()); // [0, 1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9] (V8)
console.log(stableSort([11,10,9,8,7,6,5,4,3,2,1,0])); // [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
console.log([11,10,9,8,7,6,5,4,3,2,1,0].sort(_=> 0)); // [5, 11, 9, 8, 7, 6, 10, 4, 3, 2, 1, 0] (V8)
console.log(stableSort([11,10,9,8,7,6,5,4,3,2,1,0], _=> 0)); // [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
console.log([11,10,9,8,7,6,5,4,3,2,1,0].sort((a,b)=> a.toString()[0].localeCompare(b.toString()[0]))); // [0, 11, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9] (V8)
console.log(stableSort([11,10,9,8,7,6,5,4,3,2,1,0], (a,b)=> a.toString()[0].localeCompare(b.toString()[0]))); // [0, 11, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment