Quick Sort

Write a C program to implement Quick Sort
 #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);
 }
}


DEFINITION 

A sorting technique that sequences a list by continuously dividing the list into two parts and moving the lower items to one side and the higher items to the other. It starts by picking one item in the entire list to serve as a pivot point. The pivot could be the first item or a randomly chosen one. All items that compare lower than the pivot are moved to the left of the pivot; all equal or higher items are moved to the right. It then picks a pivot for the left side and moves those items to left and right of the pivot and continues the pivot picking and dividing until there is only one item left in the group. It then proceeds to the right side and performs the same operation again 

No comments:

Post a Comment