How do I continue my while loop in relations to quicksort

Viewed 118

This is my array

 numArray: [4, 2, 6, 7, 5, 1, 8, 3]

Here I create my pivot element which I chose to be the middle one

quickSort(array = this.state.numArray) {

const pivot = array[Math.floor(array.length / 2)]; //pivot = 5
const leftArr = [];
const rightArr = [];

next up I created a function that filters bigger and smaller numbers than 5 in the left and right array(smaller numbers in left and bigger in right)No Problem so far..

const Partition = () => {
        

for (let i = 0; i < array.length; i++) {
            if (array[i] === pivot) {
                console.log(array[i]);

       

 } else if (array[i] < pivot) {
            leftArr.push(array[i]);
        } else {
            rightArr.push(array[i]);
        }
    }
}

My swap function that, which swaps elements in the array

const swap = (items, leftIndex, rightIndex) => {

            let temp = items[leftIndex];
            items[leftIndex] = items[rightIndex];
            items[rightIndex] = temp;
        }

Last but not least my sorting function. Problem here is it stops sorting way too early since the condition of the while loop is already met. How can I structure it so it keeps going till it's sorted?

const sort = (items) => {
            let i = 0;
            let j = items.length - 1;
            let newPivot = items[0];
            let sortedArray = items;

    

while (i <= j) {
    

while (sortedArray[i] < newPivot) {
            i++;
        }

        while (sortedArray[j] > newPivot) {
            j--;
        }

        if (i <= j) {
            swap(sortedArray, i, j);
            i++;
            j--;

        }
        console.log(i + " <= " + j);

    }

    return sortedArray;

}
0 Answers
Related