常用排序算法之归并排序
2016-07-26 本文已影响14人
Andy周
归并排序算法
/**
* 归并排序
* @param array
* @return
*/
public static int[] mergingSort(int[] array) {
sort(array, 0, array.length - 1);
return array;
}
public static void sort(int[] data, int left, int right) {
if (left < right) {
//找出中间索引
int center = (left + right) / 2;
//对左边数组进行递归
sort(data, left, center);
//对右边数组进行递归
sort(data, center + 1, right);
merge(data, left, center, right);
}
}
public static void merge(int[] data, int left, int center, int right) {
int[] tmpArr = new int[data.length];
int mid = center + 1;
int third = left;
int tmp = left;
while (left <= center && mid <= right) {
if (data[left] <= data[mid]) {
tmpArr[third++] = data[left++];
} else {
tmpArr[third++] = data[mid++];
}
}
while (mid <= right) {
tmpArr[third++] = data[mid++];
}
while (left <= center) {
tmpArr[third++] = data[left++];
}
while (tmp <= right) {
data[tmp] = tmpArr[tmp++];
}
}
运行
/**
* 待排序的数组
*/
private static int[] array = {
12, 10, 5, 9, 5, 32, 16, 1, 9, 99, 80, 3, 18, 19, 20, 25, 7, 15
};
public static void main(String[] args) {
int[] result = SortUtils.mergingSort(array.clone());
System.out.println(Arrays.toString(result));
}
输出
[1, 3, 5, 5, 7, 9, 9, 10, 12, 15, 16, 18, 19, 20, 25, 32, 80, 99]