C program to sort using quick sort

This program implements quick sort in C.  Quick sort is also known as partition exchange sort. In the best case quick sort makes O(n log n) comparisons and in the worst case it makes O(n2) comparisons. This algorithm selects a random number from the list as a pivot element, all the elements which are smaller than the pivot element will be shifted to the left of the pivot element and all the elements which are greater than the pivot element will be shifted to the right of the pivot element. Now the pivot element is in its final position, the algorithm repeatedly applies the above technique to the left part and the right part until the list is sorted.

 Program


//c program for sorting using quick sort
#include<stdio.h>
#include<conio.h>
int partition(int a[],int l,int r);
void quicksort(int a[],int l,int r);
void main()
{
int a[10],n,i,j,l,r,pivot;
printf("Enter the size of the array: ");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
a[n]=1000;
l=0;
r=n;
quicksort(a,l,r);
printf("Array after sorting\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}
void quicksort(int a[10],int l,int r)
{
int pivot1;
if(l<r)
{
pivot1=partition(a,l,(r+1));
quicksort(a,l,pivot1-1);
quicksort(a,pivot1+1,r);
}
}
int partition(int a[10],int l,int r)
{
int i,j;
int pivot,t;
i=l+1;
j=r-1;
pivot=a[l];
do
{
while((a[i]<=pivot)&&(i<=r))
i++;
while((a[j]>pivot)&&(j>l))
j--;
if(i<j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}}
while(i<=j);
t=a[l];
a[l]=a[j];
a[j]=t;
return j;
}

Output


Quick sort program in c
Quick Sort

No comments: