In this tutorial we learn how to sort data using Quick Sort Technique
In this Sorting technique the algorithm works on divide and conquer technique.Its take a
first element as pivot and then divide the array.The element lesser than pivot element is left side and right side always greater.The Quick sort called itself recursively.
Following code shows the Quick Sort Technique:-
#include<iostream.h>
#include<conio.h>
int partition(int a[],int l,int r)
{
int pivot,i,j,temp;
pivot=a[l];
i=l;
j=r+1;
while(1)
{
do
++i;
while((a[i]<=pivot) &&i<=r);
do
--j;
while(a[j]>pivot);
if(i>=j)
break;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
temp=a[l];
a[l]=a[j];
a[j]=temp;
return j;
}
void quicksort(int a[],int l,int r)
{
int j;
if(l<r)
{
j=partition(a,l,r);
quicksort(a,l,j-1);
quicksort(a,j+1,r);
}
}
void main()
{
int *numbers,n;
clrscr();
cout<<"\nEnter the size of array";
cin>>n;
numbers=new int[n];
cout<<"\nEnter array element:";
for(int i=0;i<n;i++)
{
cin>>numbers[i];
}
quicksort(numbers,0,n-1);
cout<<"\nSorted array";
for(i=0;i<n;i++)
{
cout<<" "<<numbers[i];
}
getch();
}
Above code Shows following output:
No comments:
Post a Comment