Three-way division

Source: Internet
Author: User

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 )?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.