Quick Sort Algorithm in C


Quicksort, or partition-exchange sort, is a sorting algorithm 
that, on average, makes O(n log n) comparisons to sort n 
items.  It was developed by Tony Hoare. Quicksort is 
faster in practice than other O(n log n) algorithms such 
as Bubble sort or Insertion Sort. Quicksort can be 
implemented with an in-place partitioning algorithm, so 
the entire sort can be done with only O(log n) additional space.

Quicksort is a comparison sort and is not a stable sort.

Its complexity is as follows:
Best Case - O(n log n)
Worst Case - O(n^2) 
Average Case - O(n log n)

Quicksort is a divide and conquer algorithm. Quicksort first 
divides a large list into two smaller sub-lists: the low 
elements and the high elements. Quicksort can then 
recursively sort the sub-lists.

The steps are:
1. Pick an element, called a pivot, from the list.

2. Reorder the list so that all elements with values less 
than the pivot come before the pivot, while all elements 
with values greater than the pivot come after it (equal 
values can go either way). After this partitioning, the 
pivot is in its final position. This is called the partition 
operation.

3. Recursively sort the sub-list of lesser elements and 
the sub-list of greater elements. The base case of the 
recursion are lists of size zero or one, which never 
need to be sorted.


Algorithm/Pseudo-code:


function quicksort('array')
  if length('array')1
     return 'array' // an array of zero or 
                   //one elements is already sorted
  select and remove a pivot value 'pivot' from 'array'
  create empty lists 'less' and 'greater'
  for each 'x' in 'array'
     if 'x''pivot' then append 'x' to 'less'
     else append 'x' to 'greater'
  return concatenate(quicksort('less'), 'pivot', 
                quicksort('greater')) // two recursive calls

Here is an Image depicting Quick Sort:

Quick Sort
In-place partition in action on a small list.  The boxed element is the pivot element,  blue elements are less or equal, and red  elements are larger.

Post a Comment

Previous Post Next Post