Quick Sort Notes
Quick Sort Notes
1. QuickSort algorithm based on the Divide and Conquer recursive algorithm .One of the fastest sorting
algorithms
The key process in quickSort is a partition().
A quick sort first selects a value, which is called the pivot value. Any element can be chosen to be a
pivot. There are many different ways to choose the pivot value. The role of the pivot value is to assist with
splitting the list
Basic idea
1. Pick one element in the array, which will be the pivot.
2. Make one pass through the array, called a partition step, re-arranging the entries so that:
a) the pivot is in its proper place.
b) entries smaller than the pivot are to the left of the pivot.
c) entries larger than the pivot are to its right.
3. Recursively apply quicksort to the part of the array that is to the left of the pivot, and to the right part of
the array.
Example :
First element taken as a pivot in an A[0…..n]
Leftmark= left+1
Rigtmark=End
By incrementing leftmark until we locate a value that is greater than the pivot value.
then decrement rightmark until we find a value that is less than the pivot value.
If rightmark> leftmark exchange these two items and then repeat the process again.
C program
#include<stdio.h>
int a[20];
void quicksort(int first,int last)
{
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(a[i]<=a[pivot]&&i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(first,j-1);
quicksort(j+1,last);
}
}
void main(){
int i, n ;
quicksort(0,n-1);