Sunday, July 9, 2017

7. Sort a given set of elements using the Quick sort method and determine the time requied to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

#include<stdio.h>
#include<conio.h>
#include<time.h>
void quicksort(int[],int,int);
int partition(int[],int,int);
void main()
{
int i,n,a[20],ch=1;
clock_t start,end;
clrscr();
while(ch)
{
printf("enter the number of elements\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
start=clock();
quicksort(a,0,n-1);
end=clock();
printf("the sorted array elements are \n");
for(i=0;i<n;i++)
printf("\n%d",a[i]);
printf("timetaken =%lf",(end-start)/CLK_TCK);
printf("\n do u want to continue (0/1) \n");
scanf("%d",&ch);
}
getch();
}
void quicksort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=partition(a,low,high);
quicksort(a,low,mid-1);
quicksort(a,mid+1,high);
}
}
int partition(int a[],int low,int high)
{
int key,i,j,temp,k;
delay(500);
key=a[low];
i=low+1;
j=high;
while(i<=j)
{
while(i<=high && key>=a[i])
i=i+1;
while(key<a[j])
j=j-1;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
{
k=a[j];
a[j]=a[low];
a[low]=k;
}
}
return j;
}

No comments:

Post a Comment