Problem: Sort an array that only contains values 1, 2, and 3 in ascending order.
Another common question: there is a sequence that can only contain red, green, and blue colors for classification, So that red is on the leftmost, and blue is on the rightmost.
Solution I: sort by count, which is intuitive.
Solution II: Perform the two-way division in the two fast rows:
Divide the array into two intervals: 1 and 1, and divide the non-1 segment into two intervals: 2 and 3.
Solution III: perform a three-way division based on the two-way division used in the quick release.
Set the original array to a with n elements.
Use three pointers: Left, middle, and right.
The value of a [0]... a [left-1] is 1.
The values of a [left]... a [Middle-1] are both 2.
The value of a [Right + 1]... a [n-1] is 3.
The value of a [Middle]... a [right] is uncertain and has not been divided.
Core steps:
1) judge whether a [right] is 3. If yes, move right to the left and continue searching. If not, a [right] And a [Middle] switch to 2 ).
2) judge the value of a [Middle]. If it is 1: exchange with a [left], left shifted right, and middle shifted right; if it is 2: middle shifted right.
3) Repeat 1 )~ 2) until middle> right
Time complexity O (N) and space complexity O (1 ).
Code:
# Include <vector> # include <iostream> using namespace STD; void sorttrisegment (vector <int> & V) {int left = 0, middle = 0, Right = (INT) v. size ()-1; while (middle <= right) {While (middle <= Right & V [right] = 3) -- right; if (middle> right) break; swap (V [right], V [Middle]); If (V [Middle] = 1) {swap (V [left], V [Middle]); ++ left ;}++ middle ;}} int main () {int arr [] = {3, 1, 2}; vector <int> V (begin (ARR ), end (ARR); sorttrisegment (V); For (Auto P: V) cout <p <""; cout <Endl; return 0 ;}
Problem extension:
Extension 1: What if it is more divided? ThisAlgorithmIs it still applicable?
Extension 2: What if the requirement is stable partitioning (I .e. stable sorting )?