您的位置:首页 > 编程语言 > Java开发

【Java笔试题】合并有序数组

2016-11-23 06:55 337 查看
1、题目

将两个有序数组合并成一个有序数组。例如,arr1 = {-1,1,3},arr2 = {0,2,4},则合并后的数组为arr = {-1,0,1,2,3,4}。

2、Java代码

public class TwoArrIntoOne {
public static void main(String args[]) {
int a[] = {-1,1,3};
int b[] = {0,2,4};
int c[] = MergeList(a, b);
if (c != null)
print(c);
else
System.out.println("");
}

public static int[] MergeList(int a[], int b[]) {  //两个有序数组的合并函数
int result[];
if (checkSort(a) && checkSort(b))  //检查传入的数组是否是有序的
{
result = new int[a.length + b.length];
int i = 0, j = 0, k = 0;   //i:用于标示a数组  j:用来标示b数组  k:用来标示传入的数组
while (i < a.length && j < b.length)
if (a[i] <= b[j]) {
result[k++] = a[i++];
} else {
result[k++] = b[j++];
}
//以下两个while循环是用来保证两个数组比较完之后剩下的一个数组里的元素能顺利传入
while (i < a.length)
result[k++] = a[i++];
while (j < b.length)
result[k++] = b[j++];
return result;
} else {
System.out.print("非有序数组,不能进行排序!");
return null;
}
}

public static boolean checkSort(int a[]) {  //检查数组是否是顺序存储的
boolean change = true;
for (int i = 0; i < a.length - 1 && change; i++) {
for (int j = i + 1; j < a.length; j++)
if (a[j - 1] > a[j])
return false;
else change = false;
}
return true;
}

public static void print(int b[]) {   //打印函数
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: