Quick Sort in CPP

 #include<iostream>

using namespace std;
int getPivotInd(int arr[],int l,int r){
    int pivot=arr[l];
    // Make j equal to the last index and i equal to "last index+1" index
    int j=r,i=r+1;
    int size=r+1-l;
    cout<<"Array received:\t";
    for(int i=l;i<=r;i++){
        cout<<arr[i]<<" ";
    }
    cout<<endl;
    cout<<"Pivot Value: "<<pivot<<"\tjth index: "<<j<<"\tith index: "<<i<<endl;
    while(j>l){
        if(arr[j]>=pivot){
            cout<<"jth elem is greater than pivot elem:\t"<<arr[j]<<">="<<pivot<<endl;
            int temp;
            // Decrease i and swap jth elem with ith elem
            i--;
            cout<<"Swapping ith elem: "<<arr[i]<<" with the jth elem: "<<arr[j]<<"\n";
            temp=arr[j];
            arr[j]=arr[i];
            arr[i]=temp;
        }
        j--;
    }
    cout<<"Loop Complete, now swapping elem before i that is "<<arr[i-1]<<"\t"
    "with pivot that is "<<arr[l]<<endl;

    // Now as the loop is complete, decrease i and then swap with the first elem,
    // that is the pivot elem(at index l)
    i--;
    int temp=arr[i];
    arr[i]=arr[l];
    // Now the pivot is at the ith ind
    arr[l]=temp;
    cout<<"Array after placing pivot at correct position:\t";
    for(int i=l;i<=r;i++){
        cout<<arr[i]<<" ";
    }
    cout<<"\n\n";
   
    // Returns the index of the pivot elem, now that pivot is swapped with the
    // ith elem, pivot is at ith index
    return i;
}
// Here l and r are the extreme indices(first and last index) of the array provided
void quickSort(int arr[],int l,int r){
    // Will do anything only if there are atleast 2 elements, otherwise just
    // ignore it
    if(l<r){
        // Get the index of the pivot, that index will be the final index of
        // the pivot elem
        int pivotInd=getPivotInd(arr,l,r);
        // Now we just need to sort the array before pivot
        quickSort(arr,l,pivotInd-1);
        // And array after pivot
        quickSort(arr,pivotInd+1,r);
    }
    else{
        // Just ignore, bcz 1 elem or 0 elems are already sorted
    }
}
int main(){
    int arr[]={10,16,8,12,15,6,3,9,5};
    // cout<<"Hello? World?\n";
    quickSort(arr,0,8);
   // Array after sorting
    // cout<<*arr<<endl;
    // cout<<sizeof(arr)<<endl;
    for(int i=0;i<sizeof(arr)/sizeof(int);i++){
        cout<<arr[i]<<" ";
    }
    // for(int i=0;i<5;i++){
    //     // cout<<"elem: "<<*arr<<" and i: "<<i<<endl;
    //     cout<<*arr+i<<endl;
    //     // cout<<*(arr+i)<<" ";
    // }
    return 0;
}

Comments

Popular Posts