- This is another divide and conquer algorithm
- Unlike mergesort, we spend time in dividing
- This is somewhat analogous to binary search
- Move all the small keys to one end of the array
- Move all of the large keys to the other end.
- Sort the two halves.
- First step is to divide, or partition the array.
int Partition(array, start, stop)
- x = array[stop]
- i = start-1
- for j = start to stop - 1
- if array[j] <= x
- i = i + 1
- exchange(array[i],array[j])
- exchange array[i+1],array[stop]
- return i+1
- Consider 8 3 5 6 2 7 4
1 2 3 4 5 6 7
-------------
8 3 5 6 2 7 4
start = 1, stop = 7
x = 4
i j array
0 1 8 3 5 6 2 7 4
1 2 3 8 5 6 2 7 4
3 3 8 5 6 2 7 4
4 3 8 5 6 2 7 4
2 5 3 2 5 6 8 7 4
6 3 2 5 6 8 7 4
3 2 4 6 8 7 5
- Note when we are done, the array is split at position 3,
- The 4 is in the final sorted spot
- Everything lower than 4 is in the bottom half of the array
- Everything larger than 4 is in the top half of the array.
- We know the split occurred at position 3.
- Note also, this is an O(n) procedure
- It is done in place.
- We want the array to be split in half, when will this happen?
- What is the worst case for the partition?
- What is the best case?
- What will the average case be?
- Note we are looking only at swaps for performance, not time.
- Randomized partition
same as above but
0. exchange(array[stop],array[start + rand()%(stop-start)])
(Remainder as before)
- This will help assure that we don't encounter the worst case.
-
QuickSort(array, start, stop)
- if start < stop
- pivot = Partition(array, start, stop)
- QuickSort( array, start, pivot-1)
- QuickSort(array, pivot+1, stop)
- What is the worst case for this entire algorithm?
- What is the best case?
- Can we check to see if the array is in order before we sort it?
- The average case is trickey, but it is O(n lg n)