Quick sort
•Internal sorting technique
•It is also called partitioning sort which
uses divide and conquer technique
Working principle
• The quick sort works by partitioning the array
A[1],A[2],…A[n] by picking some value in the
array as a pivot element.
• Pivot element is used to rearrange the
elements in the array
• Pivot can be the first element of an array and
the rest of the elements are moved so that the
elements on left side of the pivot are lesser
than the pivot
• Whereas those on the right side are greater
than the pivot
• Now the pivot element is placed in its correct
position
• Now the quick sort procedure is applied for
left array and right array in a recursive
manner.
Steps to implement quick sort
• The value of i is incremented till a[i]<= Pivot
• The value of j is decremented till a[j]> Pivot
• This process is repeated until i<j
If a[i]> pivot and a[j]<pivot and also if i<j then
swap a[i] and a[j]
If i>j then swap a[j] and a[pivot]
#include<stdio.h>
void quicksort(int number[25],int first,int last)
{
int i, j, pivot, temp;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j)
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
void main()
{
int i, count, number[25];
printf("How many elements are u going to
enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
}
example
Sort the following values using Quick Sort and
estimate its time and space complexity:
65 70 75 80 85 60 55 50 45
Analysis of quick sort
• Worst case analysis = O[N2 ]
• Best case analysis = O[N log N]
• Average case analysis = O[N log N]
advantages
• Faster than other O(N log N)
• Better cache performance & high speed
disadvantages
• Requires more memory space

DS - Quick Sort