Before encountering a very interesting topic, is about the problem of sorting algorithm:
Known: An array: array element: 0 or 1 or 2
Solve: Sort the array by 0-1-2?
1Template <classT>2 voidSwap (t& t1, t&T2)3 {4T tmp =T1;5T1 =T2;6t2 =tmp;7 }8 9 //sorting a array which the elements is 0 or 1.Ten voidSortarray_0_1 (int* Arr,intN) One { A intFirst =0;//Point to 0. - intLast = n-1;//Point to 1. - the while(First <Last ) - { - //Find the position of first 0. - while(0==Arr[first]) + { -first++; + } A at //Find The position of first 1. - while(1==Arr[last]) - { -last--; - } - in if(First <= last &&1= = Arr[first] &&0==Arr[last]) - { to Swap (Arr[first], arr[last]); +first++; -last--; the } * } $ }Panax Notoginseng - //sorting a array which the elements is 0 or 1. the voidSortarray2_0_1 (int* Arr,intN) + { A //int first = 0; //Point to 0. the intLast = n-1;//Point to 2. + intK =0;//Point to 1. - $ while(K <Last ) $ { - //Find 0. - if(1==Arr[k]) the { - while(1= = Arr[last] && k <Last )Wuyi { thelast--; - } Wu - if(K <Last ) About { $ Swap (Arr[k], arr[last]); - } - } - A if(0==Arr[k]) + { thek++; - } $ } the } the the //sorting a array which the elements is 0 or 1 or 2. the voidSortarry_0_1_2 (int* Arr,intN) - { in intFirst =0;//Point to 0. the intLast = n-1;//Point to 2. the intK =0;//Point to 1. About the while(K <Last ) the { the //Find 0. + if(0==Arr[k]) - { the while(0= = Arr[first] && First <k)Bayi { thefirst++; the } - - if(First <k) the { the Swap (Arr[k], Arr[first]); the } the } - the //Find 1. the if(1= = Arr[k] | | K = =First ) the {94k++; the } the the //Find 2.98 if(2==Arr[k]) About { - while(2= = Arr[last] && k <Last )101 {102last--;103 }104 the if(K <Last )106 {107 Swap (Arr[k], arr[last]);108 }109 } the }111}
Sorting algorithm 0-1, 0-1-2 sort