Partitioning Function from Carrano Text
The idea is to work with an array like this:
----------------------------------------------------------------------------------------
|pv|sm|sm|sm|sm|sm|sm|sm|sm|sm|sm|ge|ge|ge|ge|ge|ge|ge|ge|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|
----------------------------------------------------------------------------------------
^ ^ ^ ^
| | | |
|pivotPos |lastSmaller |firstUnknown |
| |
|first |last
CASE WHERE FIRST UNKNOWN IS SMALLER THAN THE PIVOT:
- Swap elements in positions firstUnknown and lastSmaller+1
- Increment lastSmaller
- Increment firstUnknown
CASE WHERE FIRST UNKNOWN IS GREATER THAN OR EQUAL TO THE PIVOT:
Initial Configuration, indicating that no elements are known to be smaller, greater or equal:
----------------------------------------------------------------------------------------
|pv|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|
----------------------------------------------------------------------------------------
^ ^ ^
| | |
| |firstUnknown |
| |
|lastSmaller |
| |
|pivotPos |
| |
|first |last
If the element in position first+1 is smaller than the pivot then the algorithm swaps that
element with itself and the picture changes to this:
----------------------------------------------------------------------------------------
|pv|sm|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|
----------------------------------------------------------------------------------------
^ ^ ^ ^
| | | |
| | |firstUnknown |
| | |
| |lastSmaller |
| |
|pivotPos |
| |
|first |last
On the other hand, If the element in position first+1 is greater than or equal
to the pivot then the algorithm just increments firstUnknown, and the picture
changes to this:
----------------------------------------------------------------------------------------
|pv|ge|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|uk|
----------------------------------------------------------------------------------------
^ ^ ^
| | |
| |firstUnknown |
| |
|lastSmaller |
| |
|pivotPos |
| |
|first |last
To understand how the algorithm gets started, work out some more cases:
- pivot = 1, next three elements are less, less, more
- pivot = 1, next three elements are less, more, less
- pivot = 1, next three elements are less, more, more
- pivot = 1, next three elements are more, more, less
- pivot = 1, next three elements are more, less, more
- pivot = 1, next three elements are more, less, less