合并2个有序数组

zy2419 2008-12-17 11:30:00
2个数组都是有序的 写个算法实现合并 并按照升序(降序)排列

给个完整的算法实现~
...全文
205 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
myjava_024 2008-12-18
  • 打赏
  • 举报
回复
一 建立一个第三个数组
二 每个数组中取一个数据
三 比较大小,小的放入三,否则等待下一个比较
zy2419 2008-12-18
  • 打赏
  • 举报
回复
对了 要考虑到效率哦~ 都是有序的~
大河V5 2008-12-17
  • 打赏
  • 举报
回复
3楼的相当于先合并在插入排序
但是lz已经说了:2个数组是有序的了,所以这样效率不见得高
beanj 2008-12-17
  • 打赏
  • 举报
回复

public class Test3 {
public static void main(String args[]) {
int a[] = {1,4,31,41,51};
int b[] = {11,22,32,42,52,54};
int c[] = sort(a,b);
for(int n=0; n<c.length; n++)
System.out.println(c[n]);
}

public static int[] sort(int[] a,int[] b){
int[] c=new int[a.length+b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
for(int i=0;i<c.length;i++){
for(int j=0;j<c.length-i-1;j++){
int x=c[i];
int y=c[i+1];
if(x>y){
c[i+1]=x;
c[i]=y;
}
}
}
return c;
}
}

wm920 2008-12-17
  • 打赏
  • 举报
回复


顶楼上的方法很好!
菜子儿 2008-12-17
  • 打赏
  • 举报
回复
支持楼上的。。。挺好的。。。。。
pailman 2008-12-17
  • 打赏
  • 举报
回复
public class test {
public static void main(String args[]) {
int a[] = {3,43,6,41,53};
int b[] = {2,12,32,42,152,54,9};
int res[] = new int[a.length+b.length];
System.arraycopy(a,0,res,0,a.length);
System.arraycopy(b,0,res,a.length,b.length);
sort(res);
}

public static int[] sort(int[] b){
int a[] = b;
for(int i=1;i<a.length;i++){
for(int j=0;j<a.length-i;j++){
if(a[j]>a[j+1]){
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
System.out.print("第"+i+"次循环结果:");
for(int k=0;k<a.length;k++){
System.out.print(a[k]+" ");
}
System.out.println("");
}
return a;

}
}
大河V5 2008-12-17
  • 打赏
  • 举报
回复
随便写个

public class test {
public static void main(String args[]) {
int a[] = {1,4,31,41,51};
int b[] = {11,22,32,42,52,54};
int c[] = sort(a,b);
for(int n=0; n<c.length; n++)
System.out.println(c[n]);
}

private static int[] sort(int[] a, int[] b) {
int c[] = new int[a.length+b.length];
int n = 0;
int i = 0;
int j = 0;
while(i<a.length&&j<b.length) {
if(a[i]<b[j]) {
c[n] = a[i];
n++;
i++;
}else {
c[n] = b[j];
n++;
j++;
}
}
while(i<a.length) {
c[n] = a[i];
n++;
i++;
}

while(j<b.length) {
c[n] = b[j];
n++;
j++;
}
return c;
}
}

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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