Thursday, 9 February 2012

Quick sorting


Quick sort is a divide and conquer algorithm. Its divided large list in mainly three parts:
1.     Elements less than pivot element.
2.     Pivot element.
3.     Elements greater than pivot element.
Where pivot as middle element of large list. Let’s understand through example:
List : 3 7 8 5 2 1 9 5 4

In above list assume 4 is pivot element so rewrite list as:
 3 1 2 4 5 8 9 5 7
Here, I want to say that we set the pivot element(4) which has in left side elements are less than and right hand side elements are greater than. Now you think, how’s arrange the less than and greater than elements? Be patient, you get answer soon.
Now let’s start understand the concept of quick sort. The steps are:
1.    Pick a pivot element.
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.
The base case of the recursion are lists of size zero or one, which never need to be sorted
Example of quick sort process:
Steps of quick sorting

/*c program for quick sorting*/
#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int fst, int last);
int main()
{
 int arr[30];
 int i,size;
 printf("Enter total no. of the elements : ");
 scanf("%d",&size);
 printf("Enter total %d elements : \n",size);
 for(i=0; i<size; i++)
    scanf("%d",&arr[i]);
 qsort(arr,0,size-1);
 printf("Quick sorted elements are as  : \n");
 for(i=0; i<size; i++)
    printf("%d\t",arr[i]);
 getch();
 return 0;
}
void qsort(int arr[20], int fst, int last)
{
 int i,j,pivot,tmp;
 if(fst<last)
 {
   pivot=fst;
   i=fst;
   j=last;
   while(i<j)
   {
     while(arr[i]<=arr[pivot] && i<last)
        i++;
     while(arr[j]>arr[pivot])
        j--;
     if(i<j)
     {
        tmp=arr[i];
        arr[i]=arr[j];
        arr[j]=tmp; 
     }
   }
   tmp=arr[pivot];
   arr[pivot]=arr[j];
   arr[j]=tmp;
   qsort(arr,fst,j-1);
   qsort(arr,j+1,last);
 }
}

/********* OUTPUT **********/
Output of quick sorting C program
Screen-shot of quick sorting C program

No comments:

Post a Comment