Saturday, June 13, 2015

C++ program to implement Quick Sort

/*-------------------------------------------------------------------------------------------------------------
File Name:      quick.cpp
Author:           sujith
Program:        Write a C++ program to implement Quick Sort
Date:               21-04-2015
--------------------------------------------------------------------------------------------------------------*/

#include<iostream>
#include<stdio.h>
using namespace std;
void quicksort(int a[20],int low,int high);
int partition(int a[20],int low,int high);
int main()
{

        int i,n,a[20];
        cout<<"Enter the total number of element\n";
        cin>>n;
        cout<<"Enter the Elements\n";
        for(i=0;i<n;i++)
        {
                cin>>a[i];
        }
        cout<<"After sorting\n";
        quicksort(a,0,n-1);
        for(i=0;i<n;i++){
        cout<<a[i]<<"\n";
        }
}
void quicksort(int a[],int low,int high)
{
        int keypos;
        if(low<high)
        {
                keypos=partition(a,low,high);

        quicksort(a,low,keypos-1);
        quicksort(a,keypos+1,high);
        }
}
int partition(int a[20],int low,int high)
{
        int i,j,temp,flag,key;
        key=a[low];
        i=low+1;
        j=high;
        flag=1;
        while(flag)
        {
                while(key>a[i]&&i<high){
                        i++;
                }
                while(key<a[j]){
                        j--;
                }
                if(i<j){
                        temp=a[i];
                        a[i]=a[j];
                        a[j]=temp;
                }else{
                        flag=0;
                }
        }
        temp=a[low];
        a[low]=a[j];
        a[j]=temp;
        return j;
}

OUTPUT:

[141740@localhost ~]$ g++ quick.cpp
[141740@localhost ~]$ ./a.out
Enter the total number of element
5
Enter the Elements
33        22        88        44        66
After sorting
22
33
44
66
88
[141740@localhost ~]$ g++ quick.cpp
[141740@localhost ~]$ ./a.out
Enter the total number of element
6
Enter the Elements
22        5          3          9          7          1
After sorting
1
3
5
7
9
22
[141740@localhost ~]$




No comments:

Post a Comment