2 Merge Sort
2 Merge Sort
Page 1 of 3
PROGRAM 1: Sort a given set of elements using the Quick sort method
and determine the time required 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. The elements
can be read from a file or can be generated using the random number
generator.
Quicksort(A,low, mid-1)
Quicksort(A, mid+1,high)
do i i+ 1 while (key>=a[i])
do j j1 while (key<a[j])
Quick Sort
Page 2 of 3
Program
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<sys/times.h>
clock_t start,end;
struct tms st,ed;
int partition(int low,int high,int a[])
{
int i,j,key,temp;
i=low;
j=high+1;
key=a[low];
while(i<=j)
{
do i++;
while(key>=a[i]);
do j--;
while(key<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
}
void quick_sort(int low,int high,int a[])
{
int mid;
if(low<high)
{
mid=partition(low,high,a);
quick_sort(low,mid-1,a);
Quick Sort
Page 3 of 3
quick_sort(mid+1,high,a);
}
}
int main()
{
int n,i,a[20];
printf("\nEnter the number of elements :");
scanf("%d",&n);
for (i=0;i<n;i++)
a[i]=rand()%100;
printf("\nThe array elements");
for (i=0;i<n;i++)
printf("\na[i]=%d\t",a[i]);
start=times(&st);
quick_sort(0,n-1,a);
end=times(&ed);
printf("\nThe sorted array is : ");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
printf("\nThe time taken =%f",(end-start)/CLOCKS_PER_SEC);
}
OUTPUT:
Enter the number of elements : 6
The array elements
a[0]=46 a[1]=30
a[2]=82
82
90
a[3]=90
a[3]=56
a[4]=17