package com.atguigu.me.algorithm.sort;
public class MergeSort {
private static Comparable[] cs2;
public static void main(String[] args) {
Integer[] ins = new Integer[]{9,10,4,3,5,1,6,-4,100};
sort(ins);
for(int i = 0;i<ins.length;i++){
System.out.print(ins[i]+”–>”);
}
}
public static void sort(Comparable[] a){
cs2 = new Comparable[a.length];
sort(a,0,a.length-1);
}
public static void sort(Comparable[] a,int lo,int hi){
if(hi<=lo) {
return;
}
int mid = lo + (hi – lo)/2;
sort(a,lo,mid);
sort(a,mid+1,hi);
merge(a, lo, mid, hi);
}
private static void merge(Comparable[] cs,int lo,int mid,int hi) {
int i = lo, j = mid+1;
//将排序数组赋值给一个数组
for(int k=lo;k<=hi;k++){
cs2[k] = cs[k];
}
for(int k=lo;k<=hi;k++){
if(i>mid) cs[k] = cs2[j++];//左边用尽
else if(j>hi) cs[k] = cs2[i++];//右边用尽
else if(less(cs2[j],cs2[i])) cs[k] = cs2[j++];//右边小于左边
else cs[k] = cs2[i++];//那边小就依序等于哪边
}
}
public static <T extends Comparable<T>> void exch(T[] ts,int t,int min){
T temp = ts[t];
ts[t] = ts[min];
ts[min] = temp;
}
public static <T extends Comparable<T>> boolean less(T t1,T t2){
return t1.compareTo(t2) <0;
}
}