在Java中合并并排序两个不同长度的数组 [英] Combine and sort two arrays of different length in Java

查看:431
本文介绍了在Java中合并并排序两个不同长度的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的问题"寻找解决方案,这不是一个丑陋的黑客.

I am looking for a solution for my 'problem', that isn't an ugly hack.

在我的Java代码中,我有两个数组,两个数组的长度都未知(因此它们的长度可能不同). 我想对它们进行如下排序:

In my Java code I have two arrays, both of an unknown length (so they will probably be of different length). I would like to sort them like this:

Array A: {1, 2, 3, 4, 5}
Array B: {6, 7, 8}

New Array: {1, 6, 2, 7, 3, 8, 4, 5}

有没有一种很好的方法来实现这一目标?

Is there a nice way to accomplish this?

谢谢

推荐答案

如果一个数组中的数组可能多于另一个数组,则压缩第一部分然后使用System.arrayCopy.通过删除if,它还简化了dasblinkenlight的for循环.

If it is likely that there are many more in one array than the other, it should be faster to zip the first part and then bulk copy the rest using System.arrayCopy. It also simplifies dasblinkenlight's for loop by removing the ifs.

int[] res = new int[a.length + b.length];
int p = 0;
//zip what we can
int last = Math.min(a.length, b.length);    
for (int i = 0; i != last; i++) {
    res[p++] = a[i];
    res[p++] = b[i];
}
//now add the remaining
int aRemain = a.length - last;
if(aRemain > 0) {
  System.arrayCopy(a, last, res, p, aRemain);
}
else
{
  int bRemain = b.length - last;
  if(bRemain > 0) {
    System.arrayCopy(b, last, res, p, bRemain);
  }
}

这篇关于在Java中合并并排序两个不同长度的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆