问:如何实现两个有序数组的合并(以int类型数组为例),合并成一个有序数组
面试官如果抛出这个问题,答案会有很多种,比如插入排序,比如快速排序,还有归并排序,当然首先应该想到的就是归并排序
如果面试官问我这个问题,我会这样回答:
两个有序数组合并,实现选择的排序方法有很多,如果是基本数据类型的数组,而且规模很小,元素个数在47个以内的,可以用插入排序,规模再大一些,286以内的,可以选择快速排序,否则就使用归并排序;如果是对象元素的数组可以使用归并排序。重点是:这些不用自己实现,可以直接使用Arrays.sort()方法,我们只需要将两个有序数组放到一个数组里面,排序就交给sort()方法。
至于原因,通过看源码就能明白,sort方法的原理就是我对这个问题的答案。
(当然提及的排序算法,以后的文章我会讲解一下,插入排序可以看我之前的文章算法基础学习---插入排序)
1 首先 我先实现一下两个有序数组的合并
package com.yushen.mergesort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TwoSort {
public static void main(String[] args) {
int[] a = { 1, 3, 5, 7, 9 };
int[] b = { 2, 4, 6, 8, 10 };
Object[] sumArr = sortArray(a, b);
// 数组遍历
for (int i = 0; i < sumArr.length; i++) {
System.out.println(sumArr[i]);
}
// 调用排序方法
Arrays.sort(sumArr);
// 数组遍历
for (int i = 0; i < sumArr.length; i++) {
System.out.println(sumArr[i]);
}
}
/**
* 将两个有序数组放到一个数组中(此时是无序的)
*
* @param a
* @param b
* @return
*/
private static Object[] sortArray(int[] a, int[] b) {
List<Object> resultList = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
resultList.add(a[i]);
}
for (int i = 0; i < b.length; i++) {
resultList.add(b[i]);
}
return resultList.toArray();
}
}
我是使用了List来合并两个数组的,使用ArrayList的add方法时间复杂度是O(n),少量数据元素的话,还可以,如果多了的话就要换个别的方法了。这个方式有很多,追寻jdk实现排序算法的方式,可以考虑分数组大小的情况,选择不同的合并方式。。感慨jdk的强大,研究jdk源码对学习java很重要。共勉。
2 分析一下sort方法的源码实现
首先根据参数不同,sort也有不同的实现,如果是对象数组作为参数(我的测试代码就转换成了Object数组),使用的归并排序算法。
JDK中归并的实现:
/**
* Src is the source array that starts at index 0
* Dest is the (possibly larger) array destination with a possible offset
* low is the index in dest to start sorting
* high is the end index in dest to end sorting
* off is the offset to generate corresponding low, high in src
* To be removed in a future release.
*/
private static void mergeSort(Object[] src,
Object[] dest,
int low,
int high,
int off) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i=low; i<high; i++)
for (int j=i; j>low &&
((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
swap(dest, j, j-1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
}
归并的实现讲解 以后再说吧,
3 sort方法还有几本数据类型的
比如说int,当然还有float,double等
排序源码实现:
/**
* Sorts the specified range of the array.
*
* &