## September 3, 2011

### C Program for Quick Sort

Quicksort is a sorting algorithm developed by Tony Hoare that, on average, comparisons to sort n number of items Various types of sorting techniques are available in c, Quick Sort is quite popular.

Algorithm
Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists.
The steps are:
1. Pick an element, called a pivot, from the list.
2. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements.

Here is the animation to visualize how quicksort algorithm works
Sample Output:

Code:
/* www.mycfiles.com - C Program For Quick Sort */
#include<stdio.h>
#include<conio.h>
int arr;
int comp=0;//Variable For Comparison
int mov=0;//variable For Movements
int n;
void get();
void quick(int,int);
void show();
void main(){
clrscr();
printf("- This Program Explains Sorting Using Quick Sort - \n");
get();
quick(0,n-1);
show();
getch();

}

void get(){
int i;
while(1){
printf("Enter the size of the elements :\n");
scanf("%d",&n);
if(n<=20)
break;
else
printf("Sorry the maximum no of elements is 20\n\n");
}
printf("\n");
printf("----------------------\n");
printf("Enter the values \n");
printf("----------------------\n\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
}
void quick(int l,int h)  // l = Low,h = High
{
int p,i,j;              // p = Pivot
if(l>h)
return;
i=l+1;
j=h;
p=arr[l];
while(i<=j){
while((arr[i]<=p)&&(i<=h)){
i++;
comp++;

}
comp++;
while((arr[j]>p)&&(j>=l)){
j--;
comp++;

}
comp++;
if(i<j){
int t;
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
mov++;

}
}
if(l<j){
int t;
t=arr[l];
arr[l]=arr[j];
arr[j]=t;
mov++;
}
quick(l,j-1);
quick(j+1,h);

}
void show(){
int i;
printf("\n");
printf("-----------------------\n");
printf("Sorted Array Elements\n");
printf("-----------------------\n");
for(i=0;i<n;i++){
printf("%d\n",arr[i]);

}
printf("\nNumber Of Comparison : %d",comp);
printf("\nNumber Of Movements : %d",mov);

}

Comment bellow for your Query and Feedback

### Related Posts : 