Pages - Menu

Monday, 21 July 2014

Implementation of Quick Sort in C.

Here is the code..

#include<stdio.h>

void quick(int a[], int low, int high)
{
int pos;
if(low<high)
{
pos = part(a,low,high);
quick(a,low,pos-1);
quick(a,pos+1,high);
}
}
int part(int a[], int low, int high)
{
int i,j,temp,pvno;
  i = low;
j = high;
pvno = a[i];
while(j>i)
{
while(a[i]<=pvno)
{
i++;
}
while(a[j]>=pvno)
{
j--;
}
 if(j>i)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
return i;
}
void main()
{
int n,i,high,low,a[10];

printf("SORTING OF ARRAY USING QUICK SORT");
printf("\n\n");
printf("Enter the size of array\t");
scanf("%d",&n);
printf("Enter the elements of array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
low = 0;
high = n-1;
quick(a,low,high);
printf("The quick sorted array is\n");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}

}

For Turbo C users.
#include<stdio.h>
#include<conio.h>
void quick(int a[], int low, int high)
{
int pos;
if(low<high)
{
pos = part(a,low,high);
quick(a,low,pos-1);
quick(a,pos+1,high);
}
}
int part(int a[], int low, int high)
{
int i,j,temp,pvno;
  i = low;
j = high;
pvno = a[i];
while(j>i)
{
while(a[i]<=pvno)
{
i++;
}
while(a[j]>=pvno)
{
j--;
}
 if(j>i)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
return i;
}
void main()
{
int n,i,high,low,a[10];
clrscr();
printf("SORTING OF ARRAY USING QUICK SORT");
printf("\n\n");
printf("Enter the size of array\t");
scanf("%d",&n);
printf("Enter the elements of array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
low = 0;
high = n-1;
quick(a,low,high);
printf("The quick sorted array is\n");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
getch();
}

No comments:

Post a Comment