JavaScript Program to Implement Quick Sort

JavaScript Program to Implement Quick Sort

Quick Sort is one of the most popular and efficient sorting algorithms used in programming today. It works using a smart idea called divide and conquer, where a large problem is broken into smaller parts, solved individually, and then combined. In simple terms, Quick Sort picks a value called a pivot, places it in the correct position, and then sorts the values on both sides of it. In JavaScript, Quick Sort is widely used because it is fast and performs very well on large data sets.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Quick Sort matters because it shows how powerful algorithms can be when designed carefully. Many real-world systems, such as search engines, databases, and data processing tools, rely on Quick Sort or similar logic. For beginners, learning Quick Sort is a big step forward. It helps you understand recursion, problem-solving, and efficient thinking, all of which are essential skills for writing better JavaScript programs.

Program 1: Quick Sort using basic recursion

This program shows the classic and most common way to implement Quick Sort in JavaScript. It uses recursion and a pivot to divide and sort the array.

function quickSort(arr) {

    if (arr.length <= 1) {
        return arr;
    }

    let pivot = arr[arr.length - 1];
    let left = [];
    let right = [];

    for (let i = 0; i < arr.length - 1; i++) {

        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }

    }

    return [...quickSort(left), pivot, ...quickSort(right)];

}

let numbers = [10, 7, 8, 9, 1, 5];

console.log("Sorted array:", quickSort(numbers));

This program works by choosing the last element as the pivot and dividing the remaining elements into two smaller arrays. One contains values smaller than the pivot, and the other contains larger values. Beginners find this version helpful because it clearly shows how the array is divided and sorted step by step using recursion.

Program 2: Quick Sort using the first element as pivot

This version uses the first element of the array as the pivot. It helps beginners understand that the pivot choice can change but the logic remains the same.

function quickSortFirstPivot(arr) {

    if (arr.length <= 1) {
        return arr;
    }

    let pivot = arr[0];
    let left = [];
    let right = [];

    for (let i = 1; i < arr.length; i++) {

        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }

    }

    return quickSortFirstPivot(left).concat(pivot, quickSortFirstPivot(right));

}

let values = [4, 2, 6, 9, 2];

console.log("Sorted array:", quickSortFirstPivot(values));

Here, the first value is treated as the pivot instead of the last. The rest of the logic stays the same. This example is useful for beginners because it shows that Quick Sort is flexible and not limited to one pivot strategy.

Program 3: Quick Sort using helper function and indexes

This program uses indexes instead of creating new arrays. It is closer to how Quick Sort is written in performance-focused code.

function quickSortIndex(arr, low, high) {

    if (low < high) {

        let pi = partition(arr, low, high);

        quickSortIndex(arr, low, pi - 1);
        quickSortIndex(arr, pi + 1, high);

    }

}

function partition(arr, low, high) {

    let pivot = arr[high];
    let i = low - 1;

    for (let j = low; j < high; j++) {

        if (arr[j] < pivot) {

            i++;

            let temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;

        }

    }

    let temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;

    return i + 1;

}

let data = [12, 11, 13, 5, 6];

quickSortIndex(data, 0, data.length - 1);
console.log("Sorted array:", data);

This version sorts the array in place without creating extra arrays. It is useful for beginners who want to understand how memory-efficient sorting works. Although it looks longer, breaking it into functions makes it easier to follow.

Program 4: Quick Sort in descending order

This example sorts the array from largest to smallest. It shows how a small change in comparison logic can change the sorting order.

function quickSortDesc(arr) {

    if (arr.length <= 1) {
        return arr;
    }

    let pivot = arr[arr.length - 1];
    let left = [];
    let right = [];

    for (let i = 0; i < arr.length - 1; i++) {

        if (arr[i] > pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }

    }

    return [...quickSortDesc(left), pivot, ...quickSortDesc(right)];

}

let scores = [30, 10, 50, 20, 40];

console.log("Sorted array (descending):", quickSortDesc(scores));

In this program, the comparison is reversed so larger values come first. Beginners can experiment with this version to better understand how conditions affect the result. It also helps build confidence in modifying algorithms.

Program 5: Quick Sort wrapped in a reusable function

This version focuses on clean structure and reusability. It is suitable for beginners who want to write organized JavaScript code.

function quickSortReusable(arr) {

    if (arr.length < 2) {
        return arr;
    }

    const pivotIndex = Math.floor(arr.length / 2);
    const pivot = arr[pivotIndex];
    const left = [];
    const right = [];

    for (let i = 0; i < arr.length; i++) {

        if (i === pivotIndex) continue;

        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }

    }

    return quickSortReusable(left).concat(pivot, quickSortReusable(right));

}

let items = [7, 2, 1, 6, 8, 5, 3, 4];

console.log("Sorted array:", quickSortReusable(items));

This program chooses the middle element as the pivot and organizes the logic neatly inside a function. Beginners will find this helpful because it feels close to real-world JavaScript usage. It also makes the code easy to reuse and test.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Quick Sort in JavaScript in a simple and friendly way.

Q1. What is Quick Sort in JavaScript?
Quick Sort is a fast sorting algorithm that uses a pivot to divide an array and sort it recursively. It is widely used because of its efficiency.

Q2. Why is Quick Sort faster than simple sorting algorithms?
Quick Sort reduces the number of comparisons by dividing the problem into smaller parts. This makes it much faster for large arrays.

Q3. Is Quick Sort used in real applications?
Yes, Quick Sort is used in many real-world systems, including libraries and frameworks, because it performs well in most cases.

Q4. Does Quick Sort always use recursion?
Most Quick Sort implementations use recursion, but it can also be written using loops. Recursion makes the logic easier to understand.

Q5. Should beginners learn Quick Sort?
Yes, beginners should learn Quick Sort after understanding basic sorting algorithms. It builds strong problem-solving and algorithm skills.

Conclusion

Quick Sort is one of the most important sorting algorithms to learn in JavaScript. It combines speed, efficiency, and smart problem-solving using divide and conquer. Even though it looks complex at first, breaking it into small steps makes it easier to understand.

The best way to master Quick Sort is through practice. Try changing the pivot, sorting in reverse order, or writing your own version. With regular practice, Quick Sort will help you think like a better programmer and prepare you for advanced JavaScript algorithms.

Scroll to Top