(Exercise 8.15) This exercise is a classic! It asks the readers to write a function to do Quicksort, which is a very popular sorting algorithm. Although Quicksort has a time complexity of O(n^2) in the worst case, it's time complexity is O(n log n) most of the time, which is pretty quick! So how does this algorithm work? It is simply divide and conquer!
You first pick a element from the array, which in my implementation is the first element of the array. We call this element the pivot. Then you scan from the rightmost element to find the first element that is smaller than the pivot. You swap them and do the samething from the left. You do this continuously until pivot is in the right location, i.e. all elements smaller than pivot are put on its left and all elements larger than pivot are put on its right. Then you do Quicksort on the sub-array on the left of pivot and the sub-array on the right. See? The problem size is reduced and recursion can be used to do the sorting repeatedly!
To improve the performance, we can use some small techniques to reduce the number of comparisons to be done in each loop. Also note that we need to check the size of the "sub-array" to ensure the recursion stops when the "sub-array" only has 1 element or no element!
Ok, as talk is cheap, let me show you my implementation:
#include <iostream>
using namespace std;
void swapElement( int * a, int * b )
{
int temp = *a;
*a = *b;
*b = temp;
}
void quickSort( int * const arr, const int size )
{
int *pivot = arr;
int *last = arr+size-1;
int *left = arr;
int *right = last;
int leftArrSize = 0;
int rightArrSize = 0;
while( left < right )
{
for( ; right>pivot; right-- ) // scan from the right
{
if( *pivot > *right )
{
swapElement( pivot, right );
left = pivot+1; // range for comparison narrowed
pivot = right; // update the location of pivot
right--; // move leftward from pivot
break;
}
}
for( ; left<pivot; left++ ) // scan from the left
{
if( *pivot < *left )
{
swapElement( pivot, left );
right = pivot-1; // range for comparison narrowed
pivot = left; // update the location of pivot
left++; // move rightward from pivot
break;
}
}
}
leftArrSize = pivot - arr;
rightArrSize = last - pivot;
if( leftArrSize > 1 ) quickSort( arr, leftArrSize );
if( rightArrSize > 1 ) quickSort( pivot+1, rightArrSize );
}
int main()
{
const int arrSize = 10;
int test[arrSize] = {37,2,6,4,89,8,10,12,68,45};
quickSort( test, arrSize );
for( int i=0; i<arrSize; i++ )
{
cout << test[i] << ' ';
}
cout << endl;
return 0;
}
Please contact me if you find any bugs in this program or don't understand any part of it!