Saturday, May 18, 2013

Quick sort c++ code

For in-depth understanding of Data Structure and Algorithm concepts refer :

1) INTRODUCTION TO ALGORITHMS by Coremen Introduction to Algorithms, 3rd Edition From flipkart.com
Introduction to Algorithms, 3rd Edition From amazon.com
Introduction to Algorithms from amazon.in

2) DATA STRUCTURES USING C AND C++ by Tenenbaum M Aaron - DATA STRUCTURES USING C AND C++ by Tenenbaum M Aaron from flipkart.com
Data Structures Using C and C++ (2nd Edition) from amazon.com
Data Structures Using C and C++ from amazon.in

#include<iostream.h>
#include<conio.h>
int count=0;
int partition(int a[],int  p,int r)
{

    int x,j;
    x=a[r];
    int i=p-1;
    for(j=p;j<r-1;j++)
    {
        if(a[j]<=x)
        {
            i=i+1;
            int t=a[i];
            a[i]=a[j];
            a[j]=t;
        }
    }
    int g=a[i+1];
    a[i+1]=a[r];
    a[r]=g;
    return(i+1);
}


int 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);
    }
}

void main()
{
    int a[20],n;
    cout<<"Enter the size of the array: "  ;
    cin>>n;
    cout<<"ENTER ARRAY ELEMENTS: \n";
    for(int i=0; i<n; i++)
        cin>>a[i];
    quicksort(a,0,n-1);
    cout<<"YOUR SORTED ARRAY IS: \n";
    for(int i=0;i<n;i++)
        cout<<a[i]<<endl;
    getch();
}

No comments:

Post a Comment