Tuesday, February 21, 2012

2. QUICK SORT IN C

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


ALGORITHM:
function quicksort('array')
      if length('array')1
          return 'array'  // an array of zero or one elements is already sorted
      select and remove a pivot value 'pivot' from 'array'
      create empty lists 'less' and 'greater'
      for each 'x' in 'array'
          if 'x''pivot' then append 'x' to 'less'
          else append 'x' to 'greater'
      return concatenate(quicksort('less'), 'pivot', quicksort('greater')) // two recursive calls


ANIMATION:

Sample Output:

CODE
/* COD3-AHOLIC.BLOGSPOT.COM - C Program For Quick Sort */
#include<stdio.h>
#include<conio.h>
int arr[20];
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);
}