0% found this document useful (0 votes)
17 views3 pages

1 - Quick Sort

program

Uploaded by

Charlie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views3 pages

1 - Quick Sort

program

Uploaded by

Charlie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

1. Implement and analyze Quick sort.

#include<stdio.h>
int partition(int a[], int low, int high)
{
int pivot = a[low], i=low, j= high+1;
int temp;
while(i<j)
{
do
{
i++;
}while(pivot>=a[i] && i<high);
do
{
j--;
}while(pivot<a[j]);
if(i<j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
a[low] = a[j];
a[j] = pivot;
return j;
}
void quick_sort(int a[], int low, int high)
{
int s;
if(low<high)
{
s = partition(a,low,high);
quick_sort(a,low,s-1);
quick_sort(a,s+1,high);
}
}
int main()
{
int a[50],n,low,high,i;
printf("Enter no. of elements");
scanf("%d",&n);
printf("Enter the elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
low=0;
high=n-1;
quick_sort(a,low,high);
printf("Sorted Array :");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
return 0;
}

Code added for checking execution time

#include<stdio.h>
#include<time.h>

int partition(int a[], int low, int high)


{
int pivot = a[low], i=low, j= high+1;
int temp;
while(i<j)
{
do
{
i++;
}while(pivot>=a[i] && i<high);
do
{
j--;
}while(pivot<a[j]);
if(i<j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
a[low] = a[j];
a[j] = pivot;
return j;
}
void quick_sort(int a[], int low, int high)
{
int s;
if(low<high)
{
s = partition(a,low,high);
quick_sort(a,low,s-1);
quick_sort(a,s+1,high);
}
}
int main()
{
int a[10000],n,low,high,i;
clock_t st,end
printf("Enter no. of elements");
scanf("%d",&n);
printf("Random numbers generated are");
for(i=0;i<n;i++)
{

a[i]=rand()%100;

printf("%d\t",a[i]);

}
low=0;
high=n-1;
st=clok();
quick_sort(a,low,high);
end=clock();

printf("Sorted Array :");


for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("Time required to sort the given elements is
%f",(end-st)/CLOCKS_PER_SEC);
return 0;
}

You might also like