Sunday, 26 April 2015

Cpp Program for sorting elements using Quick Sort



This is a Cpp program which sorts all the elements using Quick sort technique.

Select an element and make it as pivot , the arrangement should be such that all the elements less than pivot should on left side of it and all the elements greater than it should be on its right side. Then do the same process for the elements left and right of the pivot . the final result is the sorted array.






See the below fig ,


Quicksort-diagram.svg
"Quicksort-diagram" by Znupi - Own work. Licensed under Public Domain via Wikimedia Commons.



Download Code
PROGRAM : 

#include <iostream>

using namespace std;
void quick_sort(int [],int,int);
int main()
{
    int arr[20],n,i;
    cout << "How many numbers ? \t";
    cin >> n;

    for(i=0 ; i<n ; i++)
    {
        cout << "\nEnter number  " << i+1 << " :\t";
        cin >> arr[i];
    }
    quick_sort(arr,0,n-1);
    cout << "\n\nThe Sorted Array is:\n\n";
    for(i=0 ; i<n ; i++)
    {
        cout << arr[i] << "\t";
    }
    return 0;
}
void quick_sort(int arr[20],int low,int high)
{
    int pivot,j,temp,i;
    if(low<high)
    {
        pivot = low;
        i = low;
        j = high;
        while(i<j)
        {
            while((arr[i]<=arr[pivot])&&(i<high))
            {
                i++;
            }
            while(arr[j]>arr[pivot])
            {
                j--;
            }

            if(i<j)
            {
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }

        temp=arr[pivot];
        arr[pivot]=arr[j];
        arr[j]=temp;
        quick_sort(arr,low,j-1);
        quick_sort(arr,j+1,high);
    }
}


Download Code
OUTPUT : 


Cpp - Quick Sort