`

算法排序-归并排序 自顶向下(一)

 
阅读更多

自顶向下归并排序

 

package com.zwl.net;

/**
 * 递归归并排序
 * @author v.zhaowenlong
 * @date2013-11-22 上午10:39:37
 */
public class MergeSort {
	
	private  Comparable[] aux;
	
	
	
	public static void main(String[] args) {
		String[] a={"E","E","G","M","R","A","C","E","R","T","D","Y","H","N","J","F"};
		MergeSort ms=new MergeSort();
		ms.sort(a);
		for(int i=0;i<a.length;i++)
			System.out.print(a[i]);
		
	}
	
	public void sort(Comparable[] a){
		aux=new Comparable[a.length];
		sort(a,0,a.length-1);
	}
	
	/**
	 * 递归
	 * @param a
	 * @param li
	 * @param hi
	 */
	public void sort(Comparable[] a,int li,int hi){
		if (hi<=li) return;
		int mid=li+(hi-li)/2;
		sort(a, li, mid);
		sort(a,mid+1,hi);
		merge(a,li,mid,hi);
	}
	
	/**
	 * 原地归并排序
	 * @param a
	 * @param loj
	 * @param mid
	 * @param hi
	 */
	public void merge(Comparable[] a,int lo, int mid,int hi){
		int i=lo;
		int j=mid+1;
		
		//数组复制
		for(int k=lo;k<=hi;k++){
			aux[k]=a[k];
		}
		for(int k=lo;k<=hi;k++){
			if(i>mid)a[k]=aux[j++];
			else if(j>hi)a[k]=aux[i++];
			else if(less(aux[i],aux[j]))a[k]=aux[i++];
			else a[k]=aux[j++];
		}
	}
	
	/**
	 * 判断字母大小
	 * @param a
	 * @param b
	 * @return
	 */
	private  static boolean less(Comparable a,Comparable b){	
		int result=a.compareTo(b);
		return result<0?true:false;
	}
}

 

归并排序依赖数



 

  • 大小: 34.7 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics