QuickSort

1. Sort a given set of elements using the Quicksort 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

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int quicksort(int [],int,int);
int p(int [],int,int);
int main()
{
struct timespec ts1,ts2;
int i,a[50];
double difftime;
int n,low,high;
printf("Enter the number of array elements:\n");
scanf("%d",&n);
high=n-1;
low=0;
printf("Enter the array elements:\n");
for(i=0;i<n;i++)
{
a[i]=rand()%100;
printf("%d\t",a[i]);
}
clock_gettime(CLOCK_REALTIME,&ts1);
quicksort(a,low,high);
clock_gettime(CLOCK_REALTIME,&ts2);
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
difftime=(ts2.tv_sec*1000000000+ts2.tv_nsec)-(ts1.tv_sec*1000000000+ts1.tv_nsec);
printf("The time diff is: %e nsec\n",difftime);
}
int quicksort(int a[],int low,int high)
{
int s;
if(low<high)
{
#pragma omp parallel sections num_threads(2)
  {
s=p(a,low,high);
  #pragma omp section
quicksort(a,low,s-1);
#pragma omp section
quicksort(a,s+1,high);
}
}
}
int p(int a[],int low,int high)
{
int temp,pivot;
pivot=a[low];
int i=low+1;
int j=high;
while(i<=j)
{
while(i<=high && a[i]<pivot)
{
i++;
}
while(j>=low && a[j]>pivot)
{
j--;
}

  if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[j];
a[j]=a[low];
a[low]=temp;
return j;
}




No comments:

Post a Comment