package org.lion.euler.study.sort;
/**
* 归并排序
* 原理:两两合并
* @author lion
*
*/
public class MergeSort extends AbstractSort {
@Override
public void sort(Integer[] array) {
this.sort(array, 0, array.length - 1);
}
private void sort(Integer[] array, int begin, int end) {
int mid = (begin + end ) / 2;
if( begin < end){
this.sort(array, begin, mid);
this.sort(array, mid + 1, end);
this.merge(array, begin, mid, end);
}
}
private void merge(Integer[] array, int begin, int mid, int end){
Integer[] result = new Integer[end - begin + 1];
int beginIndex = begin;
int nextIndex = mid + 1;
int index = 0;
while(beginIndex <= mid && nextIndex <= end){
if(array[beginIndex] < array[nextIndex]){
result[index++] = array[beginIndex++];
}else {
result[index++] = array[nextIndex++];
}
}
while(beginIndex <= mid){
result[index++] = array[beginIndex++];
}
while(nextIndex <= end){
result[index++] = array[nextIndex++];
}
for (int i = 0; i < result.length; i++) {
array[begin + i] = result[i];
}
}
}