DEV Community

Ashutosh Sarangi
Ashutosh Sarangi

Posted on

1 1 1 1 1

Quick Sort using Javascript

Implementing Quick Sort is bit tricky but if you understand it and keep on practice it will be easier.


const quickSort = (arr, lo, hi) => {
    if (lo >= hi) {
        return ;
    }

    const pivotIndex = getPivotIndex(arr, lo, hi);
    quickSort(arr, lo, pivotIndex-1);
    quickSort(arr, pivotIndex+1, hi);
}

const getPivotIndex = (arr, lo, hi) => {
    const pivot = arr[hi];
    let idx = lo-1;

    for (let i = lo; i< hi; i++) {
        if (arr[i] <= pivot) {
            idx++;
            const temp = arr[i];
            arr[i] = arr[idx];
            arr[idx] = temp;
        }
    }
    idx++;
    const temp = arr[idx];
    arr[idx] = pivot;
    arr[hi] = temp;

    return idx;
}
const arr = [9,1,0,3,2,5,9,10, 11];
quickSort(arr, 0, 8);
console.log(arr); // [0, 1,  2,  3, 5, 9, 9, 10, 11]
Enter fullscreen mode Exit fullscreen mode

Try to dry run it you will get the clear picture.

Top comments (4)

Collapse
 
moopet profile image
Ben Sinclair

Is it talk like a pirate day again already?

Collapse
 
ashutoshsarangi profile image
Ashutosh Sarangi

Not Sure, I fully understand your point, Sorry. Can you explain in more details

Collapse
 
moopet profile image
Ben Sinclair

You keep saying, "Arr" :P

Thread Thread
 
ashutoshsarangi profile image
Ashutosh Sarangi

haha

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay