[英]How to debug a switch statement that does not work as expected?
I have to segregate 0s and 1s within same array. 我必须在同一个数组中隔离0和1。 I have written the logic, but not getting proper output.
我写了逻辑,但没有得到正确的输出。 Can you please check the code and let me know what is the mistake.
你能检查代码,让我知道错误是什么。
package Segregate;
public class Segregate {
public void segregate0and1(int arr[], int arr_size){
int i=0;
int j=arr_size-1;
while(j>=i){
switch(arr[i]){
case 0:{
i++;
}
case 1: {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;
}
}
}
}
public static void main(String[] args) {
Segregate seg = new Segregate ();
int arr[] = {0, 1, 0, 1, 0,0,1};
int arr_size = arr.length;
seg.segregate0and1(arr, arr_size);
System.out.print("Array after segregation is ");
for (int k = 0; k < arr_size; k++){
System.out.print(arr[k] + " ");
}
}
}
I would suggest to sort the array instead of complicating the code and logic 我建议对数组进行排序,而不是使代码和逻辑复杂化
public static void main(String[] args) {
int arr[] = { 0, 1, 0, 1, 0, 0, 1 };
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
Better way of doing things. 更好的做事方式。 Click Here for src.
点击这里查看src。
Replace this 替换它
public void segregate0and1(int arr[], int arr_size){
int i=0;
int j=arr_size-1;
while(j>=i){
switch(arr[i]){
case 0:{
i++;
}
case 1: {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;
}
}
}
}
Replace with this 替换为此
void segregate0and1(int arr[], int size)
{
/* Initialize left and right indexes */
int left = 0, right = size - 1;
while (left < right)
{
/* Increment left index while we see 0 at left */
while (arr[left] == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while (arr[right] == 1 && left < right)
right--;
/* If left is smaller than right then there is a 1 at left
and a 0 at right. Exchange arr[left] and arr[right]*/
if (left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
The break
statement is missing in the switch-case-construct. switch-case-construct中缺少
break
语句。 It should be similar to this: (I also included the default
for completeness). 它应该类似于:(我还包括完整性的
default
)。
public void segregate0and1(int arr[], int arr_size){
int i=0;
int j=arr_size-1;
while(j>=i){
switch(arr[i]){
case 0:{
i++;
break;
}
case 1: {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;
break;
}
default:
//empty
}
}
}
For testing I added a System.out.println
right behind the while
. 为了测试我加了
System.out.println
后面的权利while
。 The output is 输出是
stefan@mars:~$ java Segregate
[0, 1, 0, 1, 0, 0, 1]
[0, 1, 0, 1, 0, 0, 1]
[0, 1, 0, 1, 0, 0, 1]
[0, 0, 0, 1, 0, 1, 1]
[0, 0, 0, 1, 0, 1, 1]
[0, 0, 0, 1, 0, 1, 1]
[0, 0, 0, 0, 1, 1, 1]
The last line contains the "sorted" array. 最后一行包含“已排序”数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.