Thursday, February 7, 2013

Quick Sort example in C++ (Quick Sort.CPP)



#include <iostream>

using namespace std;

void QuickSort(int * a, int n);
void quickSort(int a[], int l, int r);

int main(int argc, char **argv)
{
int a[5];
int i=0;
while(i<5){
cin>>a[i++];
}
QuickSort(a,5);
i=0;
while(i<5){cout<<a[i++]<"\n ";cout<"--";}
return 0;
}

void QuickSort(int * a, int n){
quickSort(a, 0, n-1);
}

void quickSort(int a[], int l, int r){
if(l>=r) return;

int i=l;
int j=r + 1;

int pivot = a[l];

//Swap elements  >= pivot on left side
//with elements <= pivot on right side

while(true){
do{
i++;
}while(a[i] < pivot );

do{
j--;
}while(a[j] > pivot );

if( i >= j) break;

int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}

//Place pivot
a[l] = a[j];
a[j] = pivot;

quickSort(a, l, j-1); //Sort Left Segment
quickSort(a, j+1, r); //Sort Right Segment

}
courtesy : Data Structures, Algorithms and Applications in C++, SAHNI, McGrawHill