Below is my attempt at coding up a working algorithm in C++. The basic framework of the algorithm is as follows.
void quick_sort( vectorThe meat of the algorithm is in the partition() function. In this function, we do a few things.& v, int start, int end ) { // partition the vector int pivot = partition( v, start, end-1 ); // recursive calls for each half. if ( start < pivot -1 ) quick_sort( v, start, pivot-1 ); if ( pivot < end ) quick_sort( v, pivot, end ); return; }
- Pick a pivot value.
- Move all elements that are less than the pivot to the left of the pivot value.
- Move all elements that are greater than the pivot value to the right of the pivot value.
- Return the position of the pivot.
Here's my code for a pivot function.
int partition( vectorNotes on quick sort.& v, int start, int end ) { int pivot = v[ (start + end) / 2 ]; while( start <= end ) { while( v[ start ] < pivot ) start++; while( v[ end ] > pivot ) end--; // swap values if ( start <= end ) { int tmp = v[start]; v[start] = v[end]; v[end] = tmp; start++; end--; } } return start; }
- I think there are several other ways to write this algorithm. Different implementations can affect things like how much memory is used, whether it is stable sort, and the overall performance.
- One example where the implementation can affect performance is the choice of pivot. I set the pivot as the mid point of the array, but it can be any value. If the input was already sorted, reverse sorted, or random, the pivot position can affect the performance of the algorithm (for better or worse).
- It took me a while to get the algorithm working because it was pretty easy to to have an off by one error in many places.
No comments:
Post a Comment