合并K个有序数组-Java

时间:2021-02-07 16:36:59
package com.rao.algorithm;

import java.util.Arrays;

/**
* @author Srao
* @className MergeK
* @date 2019/12/20 23:24
* @package com.rao.algorithm
* @Description 合并K个有序数组
*/
public class MergeK { public static int[] merge(int[] arr1, int[] arr2){
int length1 = arr1.length;
int length2 = arr2.length; int[] arr = new int[length1 + length2];
int j = ;
int k = ;
int i = ;
while (j < length1 && k < length2){
if (arr1[j] <= arr2[k]){
arr[i] = arr1[j];
i++;
j++;
}else {
arr[i] = arr2[k];
i++;
k++;
}
} //把还没有进行合并的元素直接添加到新数组的后面
while (j < length1){
arr[i] = arr1[j];
i++;
j++;
}
while (k < length2){
arr[i] = arr2[k];
i++;
k++;
} return arr;
} public static void main(String[] args) {
int[] arr1 = {,,,};
int[] arr2 = {,,,};
int[] arr3 = {,,,};
int[] arr4 = {,,,}; int[] merge1 = merge(arr1, arr2);
int[] merge2 = merge(arr3, arr4);
int[] merge = merge(merge1, merge2);
System.out.println(Arrays.toString(merge));
}
}

和归并排序的思想差不多,归并排序也用到了合并有序数组