具有四种颜色的荷兰国旗算法 [英] Dutch national flag algorithm with four colors
问题描述
我经历了两种和三种颜色的解决方案,但无法获得四种颜色的解决方案.
I went through a solution for two and three colors but I am unable to get it for four colors.
请帮助.
会是rrbb????yyyggg
吗?
我们将如何交换绿色标志?
Will it be rrbb????yyyggg
?
How will we swap the green flag?
我尝试了以下解决方案,但无法将最后一个黄色替换为绿色.
I tried the solution below but it is not working with swapping the last yellow with green.
public class count123 {
// Java program to sort an array of 0, 1 and 2,3
static void sort0123(int a[], int arr_size)
{
int lo = 0;
int hi = arr_size - 1;
int mid = 0,temp=0;
int h2=arr_size - 1;
while (mid <= hi)
{
switch (a[mid])
{
case 0:
{
temp = a[lo];
a[lo] = a[mid];
a[mid] = temp;
lo++;
mid++;
break;
}
case 1:
mid++;
break;
case 2:
{
temp = a[mid];
a[mid] = a[hi];
a[hi] = temp;
hi--;
h2=hi;
break;
}
case 3:{
temp = a[mid];
a[mid] = a[h2];
a[h2] = temp;
// h2--;
//hi=h2;
break;
}
}
}
}
/* Utility function to print array arr[] */
static void printArray(int arr[], int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
System.out.print(arr[i]+" ");
System.out.println("");
}
/*Driver function to check for above functions*/
public static void main (String[] args)
{
int arr[] = {0, 1, 0,1,2,2,0,3,3,0,0,1};
int arr_size = arr.length;
sort0123(arr, arr_size);
System.out.println("Array after seggregation ");
printArray(arr, arr_size);
}
}
/*This code is contributed by Devesh Agrawal*/
推荐答案
我运行您的代码,并意识到您的代码进入了无限循环,这使您的程序无能为力.
I run your code and realized that your code goes into infinite loop, which let does your programm do nothing.
在主方法中,调用了sort0123(arr, arr_size);
,在此方法中,while (mid <= hi)
,mid = 6和hi = 9,这意味着6 <= 9
,并且由于该原因,由于以下事实,此条件无限地返回true总是在某些情况下转到情况3,而在情况3中,mid和hi的值不变.
In the main method, sort0123(arr, arr_size);
is called and within this method, while (mid <= hi)
, mid = 6 and hi = 9 and that means 6 <= 9
and because of this resaon, this condition returns true infinitely because of the fact that it goes always to the case 3 at some point and in the case 3, the values of mid and hi are not changed.
为了能够运行您的代码,您应该在逻辑上更改mid
和/或hi
的值,并使用它来改变程序的行为.
In order to be able to run your code, you should change the value(s) of mid
and/or hi
logically and with it, your program can behave, how you wanted.
这篇关于具有四种颜色的荷兰国旗算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!