0
這是一個很好的方法或最好的方法來實現Counting Sort in Javascript? 找不到標準的JS計數排序示例。Javascript Counting Sort implementation
function countingSort(arr){
var helper = []; // This helper will note how many times each number appeared in the arr
// Since JS arrary is an object and elements are not continuously stored, helper's Space Complexity minor that n
for(var i = 0; i<arr.length; i++){
if(!helper[arr[i]]){
helper[arr[i]] = 1;
}else{
helper[arr[i]] += 1;
}
}
var newArr = [];
for(i in helper){
while(helper[i]>0){
newArr.push(parseInt(i));
helper[i]--;
}
}
return newArr;
}
var arr = [5,4,3,2,1,0];
console.log(countingSort(arr)); // [0, 1, 2, 3, 4, 5]
[計數排序的維基百科條目顯示算法(https://en.wikipedia.org/wiki/Counting_sort),和鏈接到至少一個JS實現。 –
[此谷歌搜索'javascript counting sort'](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=javascript+counting+sort&*)爲我提供了在結果的第一個鏈接中的js中實現。 – csmckelvey