Three-Way Partitioning and Duplicate Keys
Maintain four regions around a pivot and explain why the element swapped in from the right still needs inspection.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 2
- Reading time
- 1 min
In this article2 chapters
Give every part of the array a meaning
Keep intervals \([0,l)\) strictly below the pivot, \([l,i)\) equal, \([i,r)\) unknown, and \([r,n)\) strictly above. Initially \(l=i=0,r=n\). If the unknown leftmost element is small, swap it with index \(l\) and advance both \(l\) and \(i\). If it is equal, advance \(i\). For a large element, decrement \(r\), swap with that new boundary and leave \(i\) unchanged. The incoming element was previously unknown.
Shrinking the unknown region proves completion
Each operation reduces \(r-i\) by one, so the pass ends after \(n\) classifications. On keys \((4,2,4,7,4)\) with pivot \(4\), only one key in each strict bucket needs further sorting. A quicksort that recurses only on the strict buckets terminates after one partition on an all-equal input. These loop invariants also let median-of-medians selection return immediately when the requested rank falls in the equal bucket.[1]