首页 > 学院 > 开发设计 > 正文

排序之归并排序

2019-11-14 08:58:03
字体:
来源:转载
供稿:网友
package com.test.sort;/**  * <Description> 归并排序:先递归再整合<br>  *   * @author liu.mingqing<br> * @version 1.0<br> * @taskId <br> * @CreateDate 2017年2月4日 <br> * @since V7.3<br> * @see com.test.sort <br> */public class MergeSort {	/**	 * Description: <br> 	 *  	 * @author liu.mingqing<br>	 * @taskId <br>	 * @param args <br>	 */	public static void main(String[] args) {		Integer[] test = {305,65,7,90,120,110,8};		mergeSort(test,0,6);		System.out.PRintln(test.toString());	}		public static <T extends Comparable<T>> void mergeSort(T[] data, int min, int max) {		if (min < max) {			int mid = (min+max)/2;			mergeSort(data, min, mid);			mergeSort(data,mid+1,max);			merge(data,min,mid,max);		}			}	/**	 * 	 * Description: merge two sorted list into one<br> 	 *  	 * @author liu.mingqing<br>	 * @taskId <br>	 * @param data	 * @param min	 * @param mid	 * @param max <br>	 */	@SuppressWarnings("unchecked")	private static <T extends Comparable<T>> void merge(T[] data, int min,int mid, int max) {		int first1 = min,last1 = mid;		int first2 = mid+1,last2 = max;		T[] temp = (T[]) new Comparable[data.length];		int index = first1;		while (first1 <= last1 && first2 <= last2) {			if (data[first1].compareTo(data[first2]) < 0){				temp[index] = data[first1];				index++;				first1++;			} else {				temp[index] = data[first2];				index++;				first2++;			}		}				while (first1 <= last1) {			temp[index] = data[first1];			index++;			first1++;		}		while (first2 <= last2) {			temp[index] = data[first2];			index++;			first2++;		}				for (index = min; index <= max; index++ ) {			data[index] = temp[index];		}	}}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表