Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

quick sort c++

#include<iostream>
using namespace std;

int solve(int arr[], int s, int e, int &pivotIndex)
{
    int i=s,j=e;
    while(i<pivotIndex && j>pivotIndex)
    {
        while(arr[i]<=arr[pivotIndex])
        {
            i++;
        }
        while(arr[j]>arr[pivotIndex])
        {
            j--;
        }
        
        if(i<pivotIndex && j>pivotIndex)
        {
            swap(arr[i++],arr[j--]);
        }
    }
    
}

int partition(int arr[], int s, int e)
{
    int count=0;
    int pivot = arr[s];
    for(int i=s+1;i<=e;i++)
    {
        if(arr[i]<=pivot)
        {
            count++;
        }
    }

    int pivotIndex = s + count;
    swap(arr[pivotIndex], arr[s]);

    return solve(arr,s,e,pivotIndex);

    /* Or we can do same here no need to call function
    int i=s,j=e;
    while(i<pivotIndex && j>pivotIndex)
    {
        while(arr[i]<=arr[pivotIndex])
        {
            i++;
        }
        while(arr[j]>arr[pivotIndex])
        {
            j--;
        }
        
        if(i<pivotIndex && j>pivotIndex)
        {
            swap(arr[i++],arr[j--]);
        }
    }

    return pivotIndex;
    
    */
}

void helper(int arr[], int s, int e)
{
    if(s>=e)
    {
        return;
    }

    // partition of array
    int p = partition(arr,s,e);

    // sorting left part
    helper(arr,s,p-1);

    // sorting right part
    helper(arr,p+1,e);

}

void quickSort(int input[], int size) {

    helper(input,0,size-1);
}

int main()
{
    int size = 6;
    int input[1000] = {5,6,0,9,1,4};
    
    quickSort(input,size);
    for(int i=0;i<size;i++)
    {
        cout<<input[i]<<" ";
    }

}
 
PREVIOUS NEXT
Tagged: #quick #sort
ADD COMMENT
Topic
Name
1+5 =