/********************************************************\
* *************** ************** *
* * * QUICK SORT * * *
* *************** ************** *
/********************************************************/
#include <iostream.h>
#include <conio.h>
#include <malloc.h>
int partition(int a[], int p, int r)
{
int x, i, j, temp;
x = a[r];
i = p-1;
for(j = p; j <= r-1; j++)
{
if(a[j] <= x)
{
i = i+1;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[i+1];
a[i+1] = a[r];
a[r] = temp;
return (i+1);
}
void quick_sort(int a[], int p, int r)
{
int q;
if(p < r)
{
q = partition(a, p, r);
quick_sort(a, p, q-1);
quick_sort(a, q+1, r);
}
}
void main()
{
int i, n, p = 0;
int* a;
clrscr();
cout << "Enter the no of elements: ";
cin >> n;
a = (int*) malloc(sizeof(int)*n);
cout << "\nEnter the elements:\n\n";
for(i = 0; i < n; i++)
{
cin >> a[i];
}
quick_sort(a, p, n);
cout << "\nSorted array is: ";
for(i = 0;i < n; i++)
{
cout << a[i] << " ";
}
getch();
}
Output :
No comments:
Post a Comment