Quick Sort algorithm:
- is one of the most efficient sorting algorithms.
- is based on divide and conquer approach.
- Successively divides the problem into smaller parts until the problem become so small that they can be directly solved.
In quick sort algorithm, you:
- Select an element from the list called as pivot.
- Partition the list into 2 parts such that:
- All the elements towards the left end of the list are smaller than the pivot.
- All the elements towards the right end of the list are greater than the pivot.
- Store the pivot at its correct position between the two parts of the list.
You repeat this process for each of the two sublists created after partitioning. This process continues untill one element is left in each sublist.
- Set pivot = arr[low]
- set i = low + 1
- set j = high
- Repeat step 6 until i < high and arr[i] < pivot //Search for element greater than pivot
- increment i by 1
- Repeat step 8 until j > low and arr[j] > pivot //Search for element smaller than pivot
- Decrement j by 1
- if i < j //If greater element is on the left of smaller element
- swap arr[i] with arr[j]
- if i<=j
- Go to step 5 //Continue the search
- if low < j
- Swap arr[low] with arr[j] //Swap pivot with last element in first part of the list
- QuickSort(low,j-1) //Apply quicksort on list left of pivot
- QuickSort(j+1,high) //Apply quicksort on list right of pivot
Implementing Quick Sort
void quicksort(int a,int low,int high);
printf(“Enter no. of elements\n”);
printf(“Enter %d numbers to be sorted\n”,high);
void quicksort(int a,int low,int high)
pivot = a[low];
first = low+1;
last = high;
while(a[first]<pivot && first < high)
while(a[last]>pivot && last > low)
temp = a[first];
a[first] = a[last];
a[last] = temp;
temp = a[low];
a[low] = a[last];
a[last] = temp;
If you found any mistakes in above code then please let us know in the comment box below.
For Gate CSE study material Click Here..!!