归并排序是一种不稳定的排序,其复杂度为O(nlogn)。基本思想:泛型是指将两个或两个以上的有序序列合并成一个有序序列。初始时将每个记录看成一个单独的有序序列,然后再对有序序列进行两两合并。
其带泛型的实现如下:
package com.xqq.归并排序;
public class MergeSort {
public static <T> void mergeSort(T [] arrays){
sort(arrays, 0, arrays.length - 1);
}
private static <T> void sort(T [] arrays, int low, int high){
int mid = (low + high)/2;
if(low < high){
// 左边
sort(arrays, low, mid);
// 右边
sort(arrays, mid + 1, high);
// 左右合并
merge(arrays, low, mid, high);
}
}
// 合并
@SuppressWarnings("unchecked")
private static <T> void merge(T [] arrays, int leftS, int leftE, int rightE){
T[] temp = arrays.clone();
int leftPos = leftS;
int rightPos = leftE + 1;
int tempPos = leftS;
while(leftPos <= leftE && rightPos <= rightE){
if(((Comparable<? super T>)arrays[leftPos]).compareTo(arrays[rightPos]) <= 0){
temp[tempPos ++] = arrays[leftPos++];
}else {
temp[tempPos ++] = arrays[rightPos++];
}
}
if(leftPos < leftE){
while(leftPos <= leftE){
temp[tempPos ++] = arrays[leftPos++];
}
}
if(rightPos < rightE){
while(rightPos <= rightE){
temp[tempPos ++] = arrays[rightPos++];
}
}
// 将合并后的数组覆盖原来的数组
for(int i = leftS; i <= rightE; i++){
arrays[i] = temp[i];
}
}
}
测试代码:
package com.xqq.归并排序;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Integer [] arrays = {4, 5, 7, 3, 3, 2, 1};
MergeSort.mergeSort(arrays);
System.out.println(Arrays.toString(arrays));
}
}
测试结果:
[1, 2, 2, 3, 3, 4, 5]