Skip to main content

QuickSort implementation in C++ (Under Hoare's method)


 


#include<iostream> 
using namespace std;

int Partition(int arr[], int lowint high)
{
    int pivot = arr[(low+high)/2];
    int i = low - 1;
    int j = high + 1;
    while(true)
    {
        do
        {
            i++;
        } 
        while(arr[i] < pivot);
            do
            {
                j--;
            } 
            while(arr[j] > pivot);
            if(i>=j)
            {
                return j;
            }
        swap(arr[i], arr[j]);
        }     
    }
                    
void QuickSort(int arr[], int lowint high)
{
    if(low<high)
    {
        int p = Partition(arr, low, high);
        QuickSort(arr, low, p);
        QuickSort(arr, p+1, high);
    }
}
    int main()
    {
        int n;
        cout<<"Enter the size of array: ";
        cin>>n;
        int arr[n];
        cout<<"Enter elements in array: ";
        for(int i=0;i<n;i++)
        {
            cin>>arr[i];
        }
        QuickSort(arr, 0, n-1);
        cout<<"Sorted array:\n"<<endl;
        for(int i=0; i < n; i++)
        {
            cout<<arr[i]<<" ";
        }    
                
    return 0;
}

Quote:

Go as far as you can see; when you get there,you'll be able to see farther...