March 18, 2018

Sorting Array - Quick sort

Quick Sort:- This technique picks up starting element as a pivot value and places it in its exact position in the array.



Code:

#include<stdio.h>


void quick(int x[],int low,int high)
{

 int pivot,i,j,t;

  if(low<high)

  {

   pivot=x[low];

   i=low+1;

   j=high;

    while(1)

    {

     while(x[i]<pivot && i<=high)

     i++;

     

     while(x[j]>pivot &&j>=low)

     j--;

     

      if(i<j)

      {

       t=x[i];

       x[i]=x[j];

       x[j]=t;

      } 

      else

      {

       break;

      }

    }

    

    x[low]=x[j];

    x[j]=pivot;

    

    quick(x,low,j-1);

    quick(x,j+1,high);

    

  }

}



void main()

{

 int x[5]={70,60,75,65,80};

 int i,n=5;

 

 printf("\nList of elements");

 for(i=1;i<n;i++)

  printf("\n%d",x[i]);

 

  quick(x,0,n-1);

 

 printf("\nAfter Sorting");

 for(i=0;i<n;i++)

  printf("\n%d",x[i]);

     

  getch();

}

Output:

Explanation:
Step 1: If there are elements in the list, then the first element is taken as pivot element.
next and last index value of the array is taken as i and j respectively.
Here i=1 and j=4
 Step 2:  Value of i is incremented until array's value x[i] is found more than the pivot value.
And value of j decremented until array's value x[j] is found less than than the pivot value.
 If value of i is less than the value of j then x[i] and x[j] are swapped and the process of step 2 is repeated again.
Else go to step 3.

Step 3: If value of i is more than the value of j, then x[j] is swapped with the value of the array's element taken as pivot.

Step 4: Now we'll see that pivot element has been reached at it's exact position in the array.
 Quick search technique is now applied at left most and right most part of the array.

No comments:

Post a Comment