Java 返回两个数组的排序组合
我的方法应该返回数组“a”和“b”的组合,并将组合作为有序数组“c”返回 对于a[5]和b[4,6]c[]应该返回[4,5,6] 最后,对于这些情况,我的代码返回[4,5],我认为排序方法中存在一个我看不到的问题Java 返回两个数组的排序组合,java,arrays,sorting,methods,Java,Arrays,Sorting,Methods,我的方法应该返回数组“a”和“b”的组合,并将组合作为有序数组“c”返回 对于a[5]和b[4,6]c[]应该返回[4,5,6] 最后,对于这些情况,我的代码返回[4,5],我认为排序方法中存在一个我看不到的问题 package combinaum; import java.util.Scanner; /** * * @author 201627010262 */ public class CombinaUm { /** * @param args the command line a
package combinaum;
import java.util.Scanner;
/**
*
* @author 201627010262
*/
public class CombinaUm {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner teclado = new Scanner (System.in);
int n1 = teclado.nextInt();
int n2 = teclado.nextInt();
int[] a = new int [n1];
int[] b = new int [n2];
for(int i = 0; i < n1; i++)
{
a[i] = teclado.nextInt();
}
for(int i = 0; i < n2; i++)
{
b[i] = teclado.nextInt();
}
System.out.println(Arrays.toString(Combine(a, b, n1, n2)));
}
public static int Combine(int a[], int b[], int n1, int n2)
{
int e = 0;
int d = 0;
int i = 0;
int n3 = n1+n2;
int [] c = new int [n3];
while(e < a.length && d <b.length )
{
if(a[e] < b[d])
{
c[i] = a[e];
e++;
i++;
}
else
{
c[i] = b[d];
d++;
i++;
}
}
while(e < a.length)
{
e++;
}
while(d <b.length)
{
d++;
}
return Arrays.copyOf(c, i);
}
}
package-combinaum;
导入java.util.Scanner;
/**
*
*@作者201627010262
*/
公共类组合{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args)
{
扫描仪teclado=新扫描仪(System.in);
int n1=teclado.nextInt();
int n2=teclado.nextInt();
int[]a=新的int[n1];
int[]b=新的int[n2];
对于(int i=0;i 虽然(en1
和n2
参数。数组知道它们的大小,您可以使用a.length
和b.length
获得它。您还需要返回int[]
以获得整个数组,而不是单个int
public static int[] Combine(int a[], int b[]) {
int[] c = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
您的意思是在方法末尾返回
c[i]
?还是返回所有c
?如果要返回所有c
,必须将方法的返回类型更改为int[]
,还可以更改打印返回值的方式。您知道数组吗。toString?是的,我应该打印a[]和b[]的排序组合,我编辑了我的问题以使其更清晰,谢谢!感谢您的洞察力,我编辑了我的问题以使其更清晰,我需要c[]作为a[]和b[]的排序组合。这与原始代码尝试执行的操作不完全相同。原始代码执行某种排序,因此如果a
和b
都按升序排序,则c
也将按升序排序。