Java实现归并算法

所谓归并算法,就是一种分治的思想;把数据进行分组,然后在排序,最后组合到一起;
以下是代码,利用Comparable实现,简单直接。

import org.junit.Test;

import java.util.Arrays;

public class Merge {
   private static Comparable[] assist;
   private static boolean greater(Comparable v,Comparable w){
       return v.compareTo(w)<0;
   }
   public static void sort(Comparable[] a){
       assist = new Comparable[a.length];
       int lo = 0;
       int hi = a.length-1;
       sort(a,lo,hi);
   }
   private 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[] a,int lo,int mid,int hi){
       int i = lo;
       int p1 = lo;
       int p2 = mid+1;
       while (p1<=mid&&p2<=hi){
           if(greater(a[p1],a[p2])){
               assist[i++] = a[p1++];
           }else {
               assist[i++] = a[p2++];
           }
       }
       while(p1<=mid){
           assist[i++] = a[p1++];
       }
       while(p2<=hi){
           assist[i++] = a[p2++];
       }
       for (int index = lo; index <=hi; index++) {
           a[index] = assist[index];
       }
   }
    @Test
    public void TestMerge(){
        Comparable[] a = new Comparable[] {9,5,6,7,8,4,3,2,1,0};
        System.out.println("待排序数组 "+Arrays.toString(a));
        sort(a);
        System.out.println(Arrays.toString(a));
    }
}

你可能感兴趣的:(java,算法,排序算法,数据结构)