package algorithm; public class MergeSort { public void merge(Integer[] array, Integer begin,Integer mid ,Integer end) { Integer[] newArray = new Integer[end + 1]; Integer sign = 0; while(begin <= end/2 && mid < end) { if(array[begin] < array[mid]) { newArray[sign] = array[begin]; begin++; } else { newArray[sign]= array[mid]; mid++; } sign++; } while(begin <= end/2) { newArray[sign] = array[begin]; begin++; } while(mid < end) { newArray[sign]= array[mid]; mid++; } for(int i = 0; i < end; i++) { array[i] = newArray[i]; } } public void sort(Integer[] array, Integer begin, Integer end) { if(end - begin > 0) { Integer mid = (begin + end)/2; sort(array,begin,mid); sort(array,mid,end); merge(array,begin,mid,end); } } }
package altest; import algorithm.MergeSort; public class AlgorithmTest { public static void main(String[] args) { MergeSort mergeSort = new MergeSort(); Integer[] array ={8,2,5,4,7,0,9,1,3,6}; mergeSort.sort(array,0,10); for(Integer i:array) { System.out.print(array [i] + " "); } } }
时间: 2024-10-19 06:03:56