0
我使用timothy roughgardens分區,他選擇了第一個元素,但它並不像我想要的那樣工作。在javascript中執行quickSort時遇到的麻煩
function swap(items, firstIndex, secondIndex){
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
function partition(arr, left, right) {
left = left || 0;
right = right || arr.length - 1;
var pivot = arr[0];
var i = left + 1;
for (var j = left + 1; j < right; j++) {
if (arr[j] < pivot) {
swap(arr, j, i); //need to swap with left most array entry which is currently bigger than pivot
i++;
}
}
//swap pivot with right most element smaller than the pivot (i-1)
swap(arr, left, i-1)
// console.log(arr);
// return i;
return i - 1;
}
function quickSort(arr, start, end) {
start = start || 0;
end = end || arr.length - 1;
var pivotNewIndex = partition(arr, start, end);
if (start < end) {
quickSort(arr, start, pivotNewIndex - 1);
quickSort(arr, pivotNewIndex + 1, end);
}
return arr;
}
var arr4 = [3, 8, 2, 1, 5];
console.log(quickSort(arr4)); --- > [ 1, 2, 3, 8, 5 ];
我在做什麼錯在這裏?我想結束正從原來的結束重新分配,我如何停止
我改變了這一點,我仍然得到[1,2,3,8,5] – WinchenzoMagnifico
另一個想法增加了 – MBo