如何合并2个已知的数组!

itfly 2006-04-19 05:56:54
有两个数组:a[]={1,2,3,4};b[]={5,6,7,8}
现在想把他们合并为:c[]={1,2,3,4,5,6,7,8}
有什么方法比较简单高效率!
...全文
3001 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
紫炎圣骑 2006-04-20
  • 打赏
  • 举报
回复
int a[] = {1,2,3};
int b[] = {4,5,6};
int c[] = new int[6];
System.arraycopy(a,0,c,0,a.length);
System.arraycopy(b,0,c,3,b.length);
for (int i = 0; i < c.length; i++)
{
System.out.println(c[i]);
}
紫炎圣骑 2006-04-20
  • 打赏
  • 举报
回复
楼上正解
网络咖啡 2006-04-20
  • 打赏
  • 举报
回复
arraycopy
  • 打赏
  • 举报
回复
正解。顶
feirne2004 2006-04-20
  • 打赏
  • 举报
回复
不错
treeroot 2006-04-20
  • 打赏
  • 举报
回复
arraycopy
Arrays.sort
alpha2007 2006-04-20
  • 打赏
  • 举报
回复
两个无序数组合并并且排序的话:
public class acopy {

public static void main(String[] args) {
int a[] = {1,13,9,4};
int b[] = {5,11,7,8};
int c[] = combine(a,b);


}
public static int[] combine(int[] a, int[] b)
{
int alen = a.length;
int blen = b.length;
int clen = alen+blen;

//数组合并
int i,j;
int temp;
int[] c = new int[clen];
System.arraycopy(a,0,c,0,alen);
System.arraycopy(b,0,c,alen,blen);

//数组元素按递增排序
for(i=0;i<clen;i++)
{
for(j=0;j<clen-i-1;j++)
{
if(c[j]>c[j+1])
{temp=c[j];
c[j]=c[j+1];
c[j+1]=temp;}
else{}

}
}

for(int k=0;k<clen;k++)
System.out.println(c[k]);
return c;

}

}
hanjienihao1 2006-04-20
  • 打赏
  • 举报
回复
class ArrayCopy {
public static void main(String[] args) {
int [] a = {1,2,3,4};
int [] b = {5,6,7,8};
int [] c = null;
int alength = a.length;
int blength = b.length;
int clength = a.length + b.length;
c = new int[clength];
System.arraycopy(a,0,c,0,alength);
System.arraycopy(b,0,c,alength,blength);
for(int i = 0;i < clength;i++) {
System.out.println(c[i]);
}
}
}
hanjienihao1 2006-04-20
  • 打赏
  • 举报
回复
lingkeylbh(凌可) 一箭双雕好!
lingkeylbh 2006-04-20
  • 打赏
  • 举报
回复
就是这样我以为楼主的意思是两个排好序的数组,组合排好序,不知道是不是多此一举了
public class arrayCombine {

/**
* @param args
*/
public static void main(String[] args) {
int a[] = {1,2,3,4};
int b[] = {5,6,7,8};
int c[] = combine(a,b);


}
public static int[] combine(int[] a, int[] b)
{
int alen = a.length;
int blen = b.length;
int clen = alen+blen;

int i,j;
int[] c = new int[clen];
for(i=0,j=0;i<alen&&j<blen;)
{
if(a[i]<b[j])
{
c[i+j]=a[i];
i++;
}
else
{
c[i+j]=b[j];
j++;
}


}

if(i==alen) System.arraycopy(b,j,c,alen+j,blen-j);

if(j==blen) System.arraycopy(a,i,c,blen+i,alen-i);
for(int k=0;k<a.length+b.length;k++)
System.out.println(c[k]);
return c;

}

}
做鸡真好吃 2006-04-20
  • 打赏
  • 举报
回复
Mark~
xiayunfei148 2006-04-19
  • 打赏
  • 举报
回复
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
yanransoft 2006-04-19
  • 打赏
  • 举报
回复
System.arraycopy()
Hmilyl 2006-04-19
  • 打赏
  • 举报
回复
System.arraycopy()
zlhran 2006-04-19
  • 打赏
  • 举报
回复
arraycopy()
rcom10002 2006-04-19
  • 打赏
  • 举报
回复
System.arraycopy()

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧