Java自顶向下的并归排序

package sortTest;

import org.junit.Test;

/**
 * Created by Main on 2018/5/14.
 */
public class MergeSort {

    private static Comparable[] aux;

    public static void sort(Comparable[] a){
        aux = new Comparable[a.length];
        sort(a,0,a.length-1);
    }

    private static void sort(Comparable[] a, int low, int high) {
        if(high<=low){
            return;
        }
        int middle = low + (high - low)/2;
        sort(a,low,middle);
        sort(a,middle+1,high);
        merge(a,low,middle,high);
    }

    private static void merge(Comparable[] a, int low, int middle, int high) {
        int i = low;
        int j = middle+1;
        for (int k = low; k <=high ; k++) {
            aux[k]=a[k];
        }
        for (int k = low; k <=high ; k++) {
            if(i>middle){
                a[k] = aux[j++];
            }else if(j>high){
                a[k] = aux[i++];
            }else if(less(aux[j],aux[i])){
                a[k] = aux[j++];
            }else{
                a[k] = aux[i++];
            }
        }
    }

    public static boolean less(Comparable a,Comparable b){
        return a.compareTo(b)<0;
    }

    @Test
    public void sortTest(){
        Integer[] numbers = new Integer[]{1,8,9,2,6,5,7};
        sort(numbers);
        for (Integer number: numbers) {
            System.out.print(number);
        }
    }
}

你可能感兴趣的:(java)