|
| 1 | +package com.xfj.sort.merge; |
| 2 | + |
| 3 | +import com.xfj.sort.insert.InsertSort; |
| 4 | +import com.xfj.sort.interfac.Sort; |
| 5 | +import com.xfj.sort.select.SelectionSort; |
| 6 | +import com.xfj.sort.util.SortGeneratorHelper; |
| 7 | + |
| 8 | +import java.lang.reflect.Array; |
| 9 | +import java.util.ArrayList; |
| 10 | +import java.util.Arrays; |
| 11 | +import java.util.List; |
| 12 | + |
| 13 | +/** |
| 14 | + * Created by asus on 2017/4/15. |
| 15 | + */ |
| 16 | +public class MergeSort<T> implements Sort{ |
| 17 | + @Override |
| 18 | + public <T extends Comparable> void sort(T[] arr, int n) { |
| 19 | + __mergeSort(arr,0,n -1); |
| 20 | + } |
| 21 | + |
| 22 | + private <T extends Comparable> void __mergeSort(T[] arr,int l,int h){ |
| 23 | + //递归退出条件 |
| 24 | + //if(l >= h) return ; |
| 25 | + if( h - l <= 15) { |
| 26 | + //当要排序数组小到一定值后,插入排序的性能要好于递归 |
| 27 | + InsertSort.sortPart(arr,l,h); |
| 28 | + return; |
| 29 | + } |
| 30 | + int mid = (l + h)/ 2; |
| 31 | + __mergeSort(arr,l,mid); |
| 32 | + __mergeSort(arr,mid + 1,h); |
| 33 | + if(arr[mid].compareTo(arr[mid+1]) > 0){ |
| 34 | + __merge(arr,l,mid,h); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + private <T extends Comparable> void __merge(T[] arr,int l,int mid,int h){ |
| 39 | + T[] aux = (T[]) createArray(arr[0].getClass(),h - l + 1); |
| 40 | + for(int i = l ;i <= h;i++){ |
| 41 | + aux[i - l] = arr[i]; |
| 42 | + } |
| 43 | + int i ; |
| 44 | + int j ; |
| 45 | + int k = l; |
| 46 | + for(i=l,j= mid +1;k <= h;k++) |
| 47 | + { |
| 48 | + if(i > mid){ |
| 49 | + arr[k] = aux[j - l]; |
| 50 | + j++; |
| 51 | + }else if( j > h){ |
| 52 | + arr[k] = aux[i - l]; |
| 53 | + i++; |
| 54 | + }else if(aux[i - l].compareTo(aux[j - l ]) < 0){ |
| 55 | + arr[k] = aux[i - l]; |
| 56 | + i++; |
| 57 | + }else{ |
| 58 | + arr[k] = aux[j -l ]; |
| 59 | + j++; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private <T extends Comparable> T[] createArray(Class<T> clazz,int initialCapacity){ |
| 65 | + //创建泛型数组的方法。 |
| 66 | + return (T[])Array.newInstance(clazz,initialCapacity); |
| 67 | + |
| 68 | + } |
| 69 | + |
| 70 | + public static void main(String[] args) { |
| 71 | + Integer[] arr = SortGeneratorHelper.generatorIntegerArray(10000, 0, 10000); |
| 72 | + SortGeneratorHelper.printArray(arr); |
| 73 | + Sort sort = new MergeSort<Integer>(); |
| 74 | + System.out.println(""); |
| 75 | + sort.sort(arr,10000); |
| 76 | + SortGeneratorHelper.printArray(arr); |
| 77 | + System.out.println(); |
| 78 | + System.out.println(SortGeneratorHelper.isSorted(arr,10000)); |
| 79 | + /* Sort iort = new InsertSort(); |
| 80 | + iort.sort(arr,10000);*/ |
| 81 | + } |
| 82 | +} |
0 commit comments