2. Quick Sort:
■ The Quick sort is an algorithm that uses divide and conquer strategy.
■ But unlike the merge sort, which splits the sequence of keys at the
midpoints, the quick sort partitions the sequence by dividing it into two
segments based on a selected pivot key.
■ There are many different versions of quick Sort that pick pivot in
different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.
3. The key process in quick Sort is partition(). Target
of partitions is, given an array and an element x of
array as pivot, put x at its correct position in sorted
array and put all smaller elements (smaller than x)
before x, and put all greater elements (greater than
x) after x. All this should be done in linear time.
4. Here’s an array to be
sorted
We’ll use the first
element as pivot
Imagine an partitioning frontier.
Element smaller than pivot go to the
left and greater than pivot will go to
right
If an element is smaller
than pivot, we extend our
frontier.
If larger element comes we keep
traversing, We cannot simply extend our
frontier, as there’s a larger element in
between.
5. We extend our frontier and
keep repeating the steps until
the entire array has been
traversed
Now element to the left
of our frontier are smaller
while those to the right
are larger than our pivot.
Now swap our pivot with
the element just before
the frontier
6. The pivot is now stationed at
it’s corresponding place. The
left and right arrays are passed
to the recursive call
We’ll now join the sorted
arrays and pivot in between
them
Our array has been sorted