Quick Sort in C++
Quick Sort Program in C++
Quick Sort, as the name indicate, sorts any list of data very quickly. Quick sort very fast data sorting technique and it requires very less additional space. It is based on the rule of Divide and Conquer(also called partition-exchange sort).
Quick sort algorithm contain mainly three parts;
- Elements less than the Pivot element
- Pivot element
- Elements greater than the pivot element
Quick Sort Program in C++
Example of Quick Sort in C++
#include<iostream.h> #include<conio.h> void quicksort(int [],int,int); int partition(int [],int,int); main() { int a[20],p,q,i,n; clrscr(); cout<<"How many elements you want to enter: "; cin>>n; for(i=0; i<n; i++) { cout<<"\nEnter any"<<n<<"Elements: "; cin>>a[i]; } p=0; q=n-1; cout<<"\n\n\nArray Befor Sorting : "; for(i=0; i<n; i++) { delay(500); cout<<a[i]; } quicksort(a,p,q); cout<<"\n\n\nArray After Sorting : "; for(i=0; i<n; i++) { delay(500); cout<<a[i]; } getch(); return 0; } void quicksort(int a[],int p,int q) { int j; if(p<q) { j=partition(a,p,q+1); quicksort(a,p,j-1); quicksort(a,j+1,q); } } int partition(int a[],int m,int p) { int v,i,j; int temp; v=a[m]; i=m;j=p; do { do { i += 1; } while(a[i]<v); do { j -= 1; } while(a[j]>v); if(i<j) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } while(i<j); a[m] =a[j]; a[j] = v; return j; }
Google Advertisment