当我通过将作为函数参数的二维数组复制到一维数组来对其进行排序时,输出是正确的,但迭代正在重复。我的做法正确吗?我使用数组“排序”来复制未排序的数组,然后对此结果集数组进行排序。
package learningJava;
import java.util.Arrays;
public class VarArgDemoThree
{
public static void main(String... args)
{
//First one D unsorted Array
int a[]= {10,2,56,17,81,92};
//Second one D unsorted Array
int b[]= {12,77,22,98,101,6};
//Static method Sort which to which both Arrays a & b are passed
Sort(a,b);
}
//Definition of Static method Sort
public static void Sort(int[]...x )//This method has a one d array as variable argument which is int[][] it get array (a[],b[])
{
//Declaring another one-d Sort of which the length is 12
int[] Sort = new int[x[0].length+x[1].length];
//Copying the one D array at location x[0] to another Array Sort using System.arraycopy
System.arraycopy(x[0], 0, Sort, 0, x[0].length);
//Copying the one D array at location x[1] to another Array Sort using System.arraycopy
System.arraycopy(x[1], 0, Sort, x[0].length, x[1].length);
//Sorting the Elements of the Array Sort
for(int i=0;i<Sort.length;i++)
{
int flag=0;
for(int j=i+1;j<Sort.length;j++)
{
if(Sort[i]>Sort[j])
{
int temp = Sort[i];
Sort[i] = Sort[j];
Sort[j] = temp;
flag=1;
}
}
System.out.print(Arrays.toString(Sort));
System.out.println();
if(flag==0)
{
break;
}
}
}
}
最佳答案
您执行的循环超出了需要的范围。
请看下面的代码:
for(int i=0;i<Sort.length;i++) // line a
{
int flag=0;
for(int j=i+1;j<Sort.length;j++) // line b
{
if(Sort[i]>Sort[j])
{
int temp = Sort[i];
Sort[i] = Sort[j];
Sort[j] = temp;
flag=1;
}
}
System.out.print(Arrays.toString(Sort)); // line c
System.out.println();
在“a 行”中,循环不断重复,直到 i == Sort.length
.
在“b 行”中,循环从 j = i + 1
开始直到j == Sort.length
.
很明显,上次“line b”中的内部循环没有运行,但“line c”正在打印 Sort
会跑。这就是为什么你要额外打印一次数组。
想象一下内循环从 Sort.length + 1
开始直到Sort.length
.
为了避免这种情况,您最好将第一个循环更改为 i < Sort.length - 1
.
其他一些事项(可选):
- 为什么你需要
flag
?您正在循环直到最后。 - 字段和局部变量的名称尽量以小写开头。例如使用
sort
而不是Sort
. - 您可以使用
System.out.print("something")
和空System.out.println()
一起,比如System.out.println("something")
.
关于java - 通过将二维数组复制到一维数组来对二维数组进行排序,输出正确,但迭代重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61812335/