You are on page 1of 3

Quick 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.

ALGORITHM Quicksort(low, high, a)


//Sorts a subarray by quicksort
//Input:
low : Position of the first element of array a
high : Position of the last element of array a
a : Array consisting of unsorted elements
//Output: a: Array consisting of sorted elements
If low<high
mid Partition(A, low, high)

// mid is a split position

Quicksort(A,low, mid-1)
Quicksort(A, mid+1,high)

ALGORITHM Partition(low, high, a)


//Partitions a subarray by using its first element as a pivot
//Input:
low : Position of the first element of array a
high : Position of the last element of array a
a : Array consisting of unsorted elements
//Output: A partition of A[low...high], with the split position returned as this
function`s value.
Key A[low]
i low , j high +1
while (i<=j)

do i i+ 1 while (key>=a[i])
do j j1 while (key<a[j])

if (i<j) swap(A[i], A[j])


end while
swap(A[low], A[j])
return j

Quick Sort

Page 2 of 3

Program
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<sys/times.h>

// for rand function


//for CLOCKS_PER_SEC
//for struct

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

The sorted array is :


17 30
46
56

82

The time taken =0.934066

90

a[3]=90

a[3]=56

a[4]=17

You might also like