我创建了自己的自定义快速排序例程来使用我拥有的自定义数据结构。它应该像常规快速排序一样工作,除了比较时我需要使用特殊函数将字符串转换为数值。
无论如何,我一定做错了什么,因为 Firefox 告诉我“错误太多递归”。
这是代码:
//Will be called on various buckets to sort by dates
function target_sort_wrapper(array) {
target_sort(array, array.length, 0, length-1);
}
//Quicksort to swap around targets based on dates
//"array" is DDATA, where DDATA[i] are targets
function target_sort(array, length, left, right) {
if (length < 2) return;
var pivotIndex = choosePivot(array, length); //returns the index
partition(array, pivotIndex, left, right);
//recursive calls now - left then right
target_sort(array, pivotIndex, 0, pivotIndex - 1);
target_sort(array, array.length - (pivotIndex+1), pivotIndex+1, array.length - 1);
}
function partition(array, pivotIndex, left, right) {
//first, put the pivot as the first element to make things easier
swap(array, pivotIndex, 0);
var pivot = array[0];
var i = left + 1;
for(var j = left + 1; j < right; j++) {
//if (array[j] > pivot) { } //do nothing, satisfies invariant
if (dateValue(array[j].date) < dateValue(pivot.date)) {
swap(array, i, j);
i = i + 1;
}
}
}
function choosePivot(array, length) {
return Math.floor(Math.random() * length); //0 (inclusive) to length (exclusive)
}
function swap(arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
谢谢你的帮助。