Saturday, 16 July 2011

Quick Sort.

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.


Algorithm:
  1. If First < Last, then
  2. Partition the elements in the sub-array First to Last so that the pivot element is in place.
  3. Apply quick sort to the first sub-array First to pivindex-1.
  4. Apply quick sort to the second sub-array pivindex+1 to Last. 


The two Stopping cases:
  1. If First=Last,Only one value in the array, So sorted.
  2. If First > Last, no values in the array, So sorted.
To Partition the array:
  1. Define the Pivot value (mostly choose first element in the array).
  2. Initialize Up to First element and Down to last element.
  3. Increment Up until Up > pivot.
  4. Decrement Down until Down <= pivot.
  5. If Up < Down exchange their values.
  6. Repeat 3,4,5 until Up meets or Passes Down.
  7. Exchange array[First] and array[Down].
  8. Define pivindex as Down.
Example :
Consider the array elements as 4,2,3,5,1.
Here First(as well as Up) and Last(as well as Down) elements are 4 and 1 respectively. Let the Pivot element be 3.



No comments:

Post a Comment