JavaScript quick sort

Question

Answers ( 1 )

  1. It's a request for an implementation of the quicksort algorithm in JavaScript.

    Quicksort is a popular sorting algorithm that uses a divide-and-conquer strategy. In JavaScript, a quick sort function typically works as follows:

    1. Choose a 'pivot' element from the array.
    2. Partition the other elements into two sub-arrays: elements less than the pivot and elements greater than the pivot.
    3. Recursively apply the above steps to the sub-arrays.
    4. Combine the results to form the sorted array.

    Here is an example of how the quicksort algorithm can be implemented in JavaScript:

    function quickSort(arr) {
        if (arr.length <= 1) {
            return arr;
        }
    
        const pivot = arr[0];
        const left = [];
        const right = [];
    
        for (let i = 1; i < arr.length; i++) {
            if (arr[i] < pivot) {
                left.push(arr[i]);
            } else {
                right.push(arr[i]);
            }
        }
    
        return quickSort(left).concat(pivot, quickSort(right));
    }
    
    // Example usage
    const array = [3, 6, 8, 10, 1, 2, 1];
    const sortedArray = quickSort(array);
    console.log(sortedArray);
    

    In this implementation:

    • The first element of the array is chosen as the pivot.
    • The quickSort function is recursively called on the left and right sub-arrays.
    • The base case for the recursion is an array with 0 or 1 element, which is already sorted by definition.
    • The sorted array is constructed by concatenating the sorted left array, the pivot, and the sorted right array.

    Note that there are other ways to implement quicksort in JavaScript, and the choice of pivot and the partitioning strategy can vary. This example provides a straightforward and easy-to-understand implementation.

Leave an answer