What's the difference between using a variable and an array element when I swap the two elements by destructuring assignment

Viewed 58

I am learning Quick Sort and here is my code below:

const pivot2 = (arr, low = 0, high = arr.length -1) => {
    let pivot = arr[low];
    let index = low;

    for(let i = low + 1; i <= high; i++){
        if(pivot > arr[i]){
            index++;
            [arr[index], arr[i]] = [arr[i], arr[index]];           
        }
    }
    [arr[low], arr[index]] = [arr[index], arr[low]];

    return index;
}

const quickSort2 = (arr, low = 0, high = arr.length - 1) => {
    if(low < high){
        let pivot = pivot2(arr, low, high); 
        quickSort2(arr, low, pivot - 1);
        quickSort2(arr, pivot + 1, high);
    }

    return arr;
}

console.log(quickSort2([5,2,1,8,4,7,6,3]));

However, when I used pivot instead of arr[low] in the pivot2 function expression, my answer was not displayed properly (it became [ 5, 5, 5, 5, 5, 7, 7, 8 ], not [ 1, 2, 3, 4, 5, 6, 7, 8 ]). I thought it would be the same result because I assigned arr[low] to pivot before. Could someone explain the concept to me or any idea about it?

0 Answers
Related