合并两个排好序的数组

将两个排好序的数组合并,并求两个排好序数组的中位数。

 1 public class MergeArray {
 2 
 3    //合并两个数组
 4     public int[] mergeSortArray(int[] arr1, int[] arr2) {
 5         int len1 = arr1.length;
 6         int len2 = arr2.length;
 7         int[] arr = new int[len1 + len2];
 8         int index1 = 0, index2 = 0;
 9         int temp = 0;
10         while (index1 < len1 && index2 < len2) {
11             if (arr1[index1] <= arr2[index2]) {
12                 arr[temp] = arr1[index1];
13                 index1++;
14             } else if (arr1[index1] > arr2[index2]) {
15                 arr[temp] = arr2[index2];
16                 index2++;
17             }
18             temp++;
19         }
20         while (index1 < len1) {
21             arr[temp] = arr1[index1];
22             temp++;
23             index1++;
24         }
25 
26         while (index2 < len2) {
27             arr[temp] = arr1[index2];
28             temp++;
29             index2++;
30         }
31         return arr;
32     }
33 
34     //计算数组的中位数
35     public long getMediumNum(int[] arr){
36         if (arr == null) {
37             return -1;
38         }
39         if (arr.length % 2 == 0) {
40             return (arr[arr.length/2] + arr[arr.length/2 -1])/2;
41         }else {
42             return arr[arr.length/2];
43         }
44     }
45     public static void main(String[] args) {
46         int[] arr = {2,4,6,10,20};
47         int[] arr1 = {4,5,8,11,15,19,21};
48         MergeArray mergeArray = new MergeArray();
49         int[] res = mergeArray.mergeSortArray(arr1, arr);
50         for (int i : res) {
51             System.out.println(i);
52         }
53     }
54 }

 

posted @ 2020-05-26 20:26  seedss  阅读(580)  评论(0编辑  收藏  举报