Mauritus national flag problem

前端 未结 6 762
时光说笑
时光说笑 2021-02-14 16:52

I\'ve made a solution for the Dutch national flag problem already.

But this time, I want to try something more difficult: the Mauritus national flag problem - 4 colours,

6条回答
  •  星月不相逢
    2021-02-14 17:41

    Here is what I came up with. Instead of colors, I am using numbers.

    // l  - index at which 0 should be inserted.
    // m1 - index at which 1 should be inserted.
    // m2 - index at which 2 should be inserted.
    // h  - index at which 3 should be inserted.
    l=m1=m2=0;
    h=arr.length-1
    while(m2 <= h) {
        if (arr[m2] == 0) {
            swap(arr, m2, l);
            l++;
    
            // m1 should be incremented if it is less than l as 1 can come after all
            // 0's
            //only.
            if (m1 < l) {
                m1++;
            }
            // Now why not always incrementing m2 as we used to do in 3 flag partition
            // while comparing with 0? Let's take an example here. Suppose arr[l]=1
            // and arr[m2]=0. So we swap arr[l] with arr[m2] with and increment l.
            // Now arr[m2] is equal to 1. But if arr[m1] is equal to 2 then we should
            // swap arr[m1] with arr[m2]. That's  why arr[m2] needs to be processed
            // again for the sake of arr[m1]. In any case, it should not be less than
            // l, so incrmenting.
            if(m2

    Similarly we can write for five flags.

        l=m1=m2=m3=0;
        h= arr.length-1;
        while(m3 <= h) {
            if (arr[m3] == 0) {
                swap(arr, m3, l);
                l++;
                if (m1 < l) {
                    m1++;
                }
                if(m2

提交回复
热议问题