Pages

Friday, 3 April 2015

Quick Sort Using C++

Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are: 
1. Pick an element, called a pivot, from the array. 
2. Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
3. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.


/* C++ Program to implement Quick Sort */ 
#include<iostream>
using namespace std;

void QUICKSORT(int [],int ,int );
int PARTITION(int [],int,int );

int main()
{
    int n;
    cout<<"Enter the size of the array"<<endl;
    cin>>n;
    int a[n];
    cout<<"Enter the elements in the array"<<endl;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    cout<<"sorting using quick sort"<<endl;
    int p=1,r=n;
    QUICKSORT(a,p,r); 
    cout<<"sorted form"<<endl;
   for(int i=1;i<=n;i++)
   {
       cout<<"a["<<i<<"]="<<a[i]<<endl;
   }
     return 0;
}

void QUICKSORT(int a[],int p,int r)
    {
        int q;
        if(p<r)
        {
         q=PARTITION(a,p,r);
         QUICKSORT(a,p,q-1);
         QUICKSORT(a,q+1,r);
        }
    }

 int PARTITION(int a[],int p,int r)
    {
        int temp,temp1;
        int x=a[r];
        int i=p-1;
        for(int j=p;j<=r-1;j++)
        {
            if(a[j]<=x)
            {

                i=i+1;
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
        temp1=a[i+1];
        a[i+1]=a[r];
        a[r]=temp1;
        return i+1;
    }
 
//Output of the above program
 

Quick Sort Using C++
Quick Sort Using C++


Related Programs:-

Merge Sort using C++

Heap Sort using C++

Insertion Sort using C++

Find 2's Complement of a given number

Prints X with probability=0.1, Y with probability=0.3, and Z with probability=0.6

1 comment:

Back to Top