Mauritus national flag problem

前端 未结 6 749
时光说笑
时光说笑 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:43

    let a:string[] = ['1','2','1','0','2','4','3','0','1','3'];
    
    function sort3(a:string[]):void{
        let low = 0;
        let mid1 = 0;
        let mid2 = 0;
        let mid3 = 0;
        let high = a.length - 1;
        while(mid3<=high){
            switch(a[mid3]){
                case '0': [a[mid3],a[low]] = [a[low],a[mid3]];
                        low++;
                        if(mid1 < low)
                        mid1++;
                        if(mid2 < mid1)
                        mid2++;
                        if(mid3 < mid2)
                        mid3++;
                        break;
    
                case '1': [a[mid3],a[mid1]] = [a[mid1],a[mid3]];
                        mid1++;
                        if(mid2 < mid1)
                        mid2++;
                        if(mid3 < mid2)
                        mid3++
                        break;
    
                case '2': [a[mid2],a[mid3]] = [a[mid3],a[mid2]];
                            mid2++;
                            mid3++;
                       break;
    
                case '3':
                        mid3++;break;
    
                case '4': [a[mid3],a[high]] = [a[high],a[mid3]];
                            high--;
            }
        }
    }
    

提交回复
热议问题