简体   繁体   中英

javascript quicksort different output than expected

I was learning quicksort and I wrote this code (half copied) but for some reason it doesn't work. All I am trying to do is sort an array in ascending order using quicksort.

const arr = [5, 2, 4, 2, 1, 9, 5, 8, 7, 4];

const quickSort = (arr, left = 0, right = arr.length - 1) => {
    if (left < right) {
        let pivotIndex = pivot(arr, left, right)
        //LEFT HALF
        quickSort(arr, left, pivotIndex - 1);
        //RIGHT HALF
        quickSort(arr, pivotIndex + 1, right);
    }
    return arr;
}

Pivot function

const pivot = (arr, start = 0, end = arr.length - 1) => {
    const swap = (arr, i, j) => {
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }

    let pivot = arr[start];
    let swapIndex = start;

    for (let i = 1; i < end; i++) {
        if (arr[i] < pivot) {
            swapIndex++;
            swap(arr, swapIndex, i);
        }
    }
    swap(arr, start, swapIndex)
    return swapIndex
}

Output

[
  1,         5,
  8,         7,
  undefined, undefined,
  9,         undefined,
  undefined, 2,
  2,         4,
  4,         5
]

Please tell me the error and the solution. I understand how quicksort works but still having some difficulty in understanding the logic of the code.

The logic in pivot is wrong.

Lets look at the first iteration of pivot:

start = 0;
end = 9;
pivot = 5;
swapIndex = 0;

i = 1;

if(arr[i] < pivot)
{
  swapIndex++;
  swap(arr, swapIndex, i)
}

// this evaluates to:

if(2 < 5)
{
  swapIndex = 1;
  swap(arr, swapIndex, 1);
}

So no swapping takes place.

Does the same happen for the next i ?

if(4 < 5)
{
  swapIndex = 2;
  swap(arr, swapIndex, 2);
}

Yes, and the same happens for the next two i s. The next chance for a swap is at the end, when i would be 9, but the test is for i < end , so that swap never happens.

I believe it's more usual to pivot from the larger index, and only pivot from start to end.

 const pivot = (arr, start = 0, end = arr.length - 1) => { const swap = (arr, i, j) => { [arr[i], arr[j]] = [arr[j], arr[i]]; }; let pivot = arr[end]; let swapIndex = start-1; for (let i = start; i <= end-1; i++) { if (arr[i] < pivot) { swapIndex++; swap(arr, swapIndex, i); } } swap(arr, swapIndex+1, end) return swapIndex+1 } let inp = [5, 2, 4, 2, 1, 9, 5, 8, 7, 4]; const quickSort = (arr, left = 0, right = arr.length - 1) => { if (left < right) { let pivotIndex = pivot(arr, left, right) //LEFT HALF quickSort(arr, left, pivotIndex-1); //RIGHT HALF quickSort(arr, pivotIndex + 1, right); } return arr; } console.log(quickSort(inp).join(','));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM