Quicksort JavaScript

 

Quick Sort Code in JavaScript

Read Similar Posts:
1. Quick Sort In C 
2. Quick Sort Time Complexity

//Code Starts From Here

function partition(a, left, right, n)
{
    var piv, i, j, temp;
    piv = left;
    i = piv + 1;
    j = right;
    while(i<=j)
    {
        while(a[piv] < a[j] && piv < j)
        {
            j--;
        }
        if(a[piv] > a[j] && piv < j)
        {
            temp = a[piv];
            a[piv] = a[j];
            a[j] = temp;
            piv = j;
            j--;
        }
        while(a[i] < a[piv] && i < piv)
        {
            i++;
        }
        if(a[i] > a[piv] && i < piv)
        {
            temp = a[piv];
            a[piv] = a[i];
            a[i] = temp;
            piv = i;
            i++;
        }
    }
    return piv;

}

function QuickSort(a, left, right, n)
{
    if(left < right)
    {
        var ind = partition(a, left, right, n);
        QuickSort(a, left, ind-1, n);
        QuickSort(a, ind+1, right, n);
    }
}
    
const DataArray = [2, 5, 1, 4, 3, 10, 9, 8, 6, 7];
console.log('Before Sorting: '+DataArray)
QuickSort(DataArray, 0, DataArray.length-1, DataArray.length);
console.log('After Sorting: '+DataArray); 

//Code Ends Here


Sample Intput:
2, 5, 1, 4, 3, 10, 9, 8, 6, 7

Sample Output:
Before Sorting: 2, 5, 1, 4, 3, 10, 9, 8, 6, 7
After Sorting: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Post a Comment

Previous Post Next Post