[html]
package com.andyidea.algorithms; import Java.lang.reflect.Array; /** * 归并排序法 * @author Andy.Chen * * @param <T> */ public class MergeSort<T extends Comparable<T>> extends Sorter<T> { @SuppressWarnings("unchecked") @Override public void sort(T[] array, int from, int len) { if(len<=1) return; T[] temp = (T[])Array.newInstance(array[0].getClass(), len); mergeSort(array, from, from+len-1, temp); } /** * 分成两组排序 * @param array * @param from * @param to * @param temporary */ private final void mergeSort(T[] array,int from,int to,T[] temporary){ if(to<=from) return; int middle = (from+to)/2; mergeSort(array, from, middle, temporary); mergeSort(array, middle+1, to, temporary); merge(array, from, to, middle, temporary); } /** * 把排序好的序列合并 * @param array * @param from * @param to * @param middle * @param temporary */ private final void merge(T[] array,int from,int to,int middle,T[] temporary){ int k=0; int leftIndex=0; int rightIndex=to-from; System.arraycopy(array, from, temporary, 0, middle-from+1); for(int i=0;i<to-middle;i++){ temporary[to-from-i]=array[middle+i+1]; } while(k<to-from+1){ if(temporary[leftIndex].compareTo(temporary[rightIndex])<0) { array[k+from]=temporary[leftIndex++]; } else { array[k+from]=temporary[rightIndex--]; } k++; } } }排序算法(Java实现):Shell排序和归并排序
内容版权声明:除非注明,否则皆为本站原创文章。