我需要一些帮助在 JavaScript 中实现基数排序算法。
我在网上找到了这个示例,代码如下,但我不明白如何调用该函数,因为它似乎是为该站点量身定制的:
// Radix sort a (base 2)
// Numbers must be in the range 0 to 2**31 - 1
function radixSort() {
readArray('i');
var b0 = new obj(); // Bin for 0 digits
var b1 = new obj(); // Bin for 1 digits
for (var i=0; i<32; ++i) {
if (form.step.checked) { // Single step
writeArray('i','a');
if (!confirm("Sort on bit "+i))
return;
}
var mask = 1<<i; // Digit (2**i)
var biggest = 2<<i; // If all of a is smaller, we're done
var zeros=0; // Number of elements in b0, b1
var ones=0;
var found=false; // Any digits past i?
for (var j=0; j<n; ++j) { // Sort into bins b0, b1
if ((a[j] & mask) == 0)
b0[zeros++] = a[j];
else
b1[ones++] = a[j];
if (a[j]>=biggest) // Any more digits to sort on?
found=true;
}
for (j=0; j<zeros; ++j) // Concatenate b0, b1 back to a
a[j]=b0[j];
for (j=0; j<ones; ++j)
a[j+zeros]=b1[j];
form.imoves.value = parseInt(form.imoves.value)+n;
if (!found)
break;
}
writeArray('i','a');
}