Quick Sort Algorithm
Quick Sort Algorithm
Data Structures
Quick sort is a fast sorting algorithm used to sort a list of elements. Quick sort algorithm is invented by C.
A. R. Hoare.
The quick sort algorithm attempts to separate the list of elements into two parts and then sort each part
recursively. That means it use divide and conquer strategy. In quick sort, the partition of the list is
performed based on the element called pivot. Here pivot element is one of the elements in the list.
The list is divided into two partitions such that "all elements to the left of pivot are smaller than the
pivot and all elements to the right of pivot are greater than or equal to the pivot".
In Quick sort algorithm, partitioning of the list is performed using following steps...
Step 1 - Consider the first element of the list as pivot (i.e., Element at first position in the list).
Step 2 - Define two variables i and j. Set i and j to first and last elements of the list respectively.
int pivot,i,j,temp;
pivot = first;
i = first;
j = last;
i++;
j--;
temp = list[i];
list[i] = list[j];
list[j] = temp;
temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
quickSort(list,first,j-1);
quickSort(list,j+1,last);
Example
To sort an unsorted list with 'n' number of elements, we need to make ((n-1)+(n-2)+(n-3)+......+1) = (n (n-
1))/2 number of comparisions in the worst case. If the list is already sorted, then it requires 'n' number
of comparisions.
#include<stdio.h>
#include<conio.h>
void main(){
int list[20],size,i;
scanf("%d",&size);
scanf("%d",&list[i]);
quickSort(list,0,size-1);
printf(" %d",list[i]);
getch();
int pivot,i,j,temp;
pivot = first;
i = first;
j = last;
while(i < j){
i++;
j--;
if(i <j){
temp = list[i];
list[i] = list[j];
list[j] = temp;
temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
quickSort(list,first,j-1);
quickSort(list,j+1,last);
Output