Quicksort and its Implementation in ‘C’

Like Merge Sort, Quicksort is a divide and conquer algorithm. Quicksort first divides the array into two smaller sub-arrays around a picked element called Pivot. Then recursively sort the sub-arrays. It works as follows:

  1. Pick an element, called a pivot, from the array.
  2. Reorder the array such that all the elements before pivot are less than pivot value, while all elements after pivot are grater than or equal to pivot. After this operation, the pivot is in its final position. This is the key process in quicksort, called the partition().
  3. Recursively apply this to the sub-arrays before and after the pivot. Look at this example.

There are different variants of Quicksort that pick pivots in different ways:

  1. First element of array.
  2. Last element of array.(used in the following implementation)
  3. Random element of array.
  4. Middle index element of array.

Complexities

Time complexity : O( N log N --  N log N -- N² ) [Best -- Average -- Worst] 
Memory          :  O(N or log N) # auxiliary i.e. apart from storing input array 
Stable          :  No i.e. can change relative order of elements with same key
# N being the number of elements in the array

Other popular sorting algorithms’ complexities are given here.

Usage and advantages

Continue reading

Advertisements