Here's a detailed example of the partitioning algorithm. Suppose our vector has 12 elements:
And suppose we have already done some partitioning, and we are in a nested recursive call:
recursive_sort(v, 5, 7, 0);This means we need to sort the last seven elements of the vector. Below, I've colored those elements light orange. Suppose we use v[start] as our pivot. Then, our pivot is 13. We start partitioning with our left pointer equaling 6 and the right pointer equaling 11:
Next, we move the left pointer to the right until it is pointing to an element ≥ 13. That moves it to equal 7. The right pointer is already pointing to an element ≤ 13:
Now, we swap them, increment the left pointer and decrement the right pointer:
Since the left pointer is pointing to an element ≥ 13 and the right pointer is pointing to an element ≤ 13, we swap them, increment the left pointer and decrement the right pointer:
We increment the left pointer again, and now it is pointing past the right pointer, so we are almost done:
Our final move is to swap the pivot with the rightmost element in the left set (element #9 with a value of 10). Then we are going to recursively sort the left and right sets (colored very light blue below) with the two calls:
recursive_sort(v, 5, 4, 0); recursive_sort(v, 10, 2, 0);