数组合并、查找、排序

  • 数十万很大的两个有序数组找出相同数据
  • 把以下两个有序的整形数组拼接成一个新的有序数组,并返回该数组

数十万很大的两个有序数组找出相同数据

根据有序的特性针对性遍历,代码可能会有一些问题,还望大佬指正

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 数十万很大的两个有序数组找出相同数据
*/
public class ArrayEqual {
public static void main(String[] args) {
int[] m = {2, 4, 6, 9, 12, 13, 15, 16};
int[] n = {3, 5, 9, 12, 15};
Search(m, n);
}

private static void Search(int[] m, int[] n) {
int minLength = Math.min(m.length, n.length);
int i = 0, j = 0;
while (j < minLength || i < minLength) {
if (m[i] == n[j]) {
System.out.println(m[i]);
i++;
j++;
} else if (m[i] < n[j]) {
i++;
} else {
j++;
}
}
}
}

把以下两个有序的整形数组拼接成一个新的有序数组,并返回该数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class arraySort {
public static void main(String[] args) {
int arrayA[] = {1, 3, 4, 12, 55, 56, 71, 81};
int arrayB[] = {2, 12, 13, 19, 32, 55, 57, 100};
System.out.println(Arrays.toString(sumArray(arrayA,arrayB)));
}

private static int[] sumArray(int[] a, int[] b) {
// 定义一个新数组,长度为两个数组长度之和
int[] result = new int[a.length + b.length];
//i:a数组下标 j:b数组下标 k:新数组下标
int i = 0, j = 0, k = 0;
//按位循环比较两个数组,较小元素的放入新数组,下标加一(注意,较大元素对应的下标不加一),直到某一个下标等于数组长度时退出循环
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;
}
}