Repository navigation
Expand file tree
/
Copy pathMergeSort.java
More file actions
82 lines (74 loc) · 2.39 KB
/
Copy pathMergeSort.java
File metadata and controls
82 lines (74 loc) · 2.39 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.xfj.sort.merge;
import com.xfj.sort.insert.InsertSort;
import com.xfj.sort.interfac.Sort;
import com.xfj.sort.select.SelectionSort;
import com.xfj.sort.util.SortGeneratorHelper;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by asus on 2017/4/15.
*/
public class MergeSort<T> implements Sort{
@Override
public <T extends Comparable> void sort(T[] arr, int n) {
__mergeSort(arr,0,n -1);
}
private <T extends Comparable> void __mergeSort(T[] arr,int l,int h){
//递归退出条件
//if(l >= h) return ;
if( h - l <= 15) {
//当要排序数组小到一定值后,插入排序的性能要好于递归
InsertSort.sortPart(arr,l,h);
return;
}
int mid = (l + h)/ 2;
__mergeSort(arr,l,mid);
__mergeSort(arr,mid + 1,h);
if(arr[mid].compareTo(arr[mid+1]) > 0){
__merge(arr,l,mid,h);
}
}
private <T extends Comparable> void __merge(T[] arr,int l,int mid,int h){
T[] aux = (T[]) createArray(arr[0].getClass(),h - l + 1);
for(int i = l ;i <= h;i++){
aux[i - l] = arr[i];
}
int i ;
int j ;
int k = l;
for(i=l,j= mid +1;k <= h;k++)
{
if(i > mid){
arr[k] = aux[j - l];
j++;
}else if( j > h){
arr[k] = aux[i - l];
i++;
}else if(aux[i - l].compareTo(aux[j - l ]) < 0){
arr[k] = aux[i - l];
i++;
}else{
arr[k] = aux[j -l ];
j++;
}
}
}
private <T extends Comparable> T[] createArray(Class<T> clazz,int initialCapacity){
//创建泛型数组的方法。
return (T[])Array.newInstance(clazz,initialCapacity);
}
public static void main(String[] args) {
Integer[] arr = SortGeneratorHelper.generatorIntegerArray(10000, 0, 10000);
SortGeneratorHelper.printArray(arr);
Sort sort = new MergeSort<Integer>();
System.out.println("");
sort.sort(arr,10000);
SortGeneratorHelper.printArray(arr);
System.out.println();
System.out.println(SortGeneratorHelper.isSorted(arr,10000));
/* Sort iort = new InsertSort();
iort.sort(arr,10000);*/
}
}