归并排序
归并排序
归并排序是一种概念上最简单的排序算法,与快速排序一样,归并排序也是基于分治法的。归并排序将待排序的元素序列分成两个长度相等的子序列,为每一个子序列排序,然后再将他们合并成一个子序列。合并两个子序列的过程也就是两路归并。
public class MergeSort {
public static void main(String[] args) {
int[] arr = {1, 4, 6, 3, 2, 7, 4, 9, 20, 10};
int[] copy = new int[10];
mergeArr(arr, copy, 0, arr.length - 1);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void mergeArr(int[] arr, int[] copy, int low, int high) {
if (low == high)
return;
int mid = (low + high) / 2;
mergeArr(arr, copy, low, mid);
mergeArr(arr, copy, mid + 1, high);
int i = mid;
int j = high;
int copyIndex = high;
while (i >= low && j > mid) {
if (arr[i] > arr[j]) {
copy[copyIndex--] = arr[i--];
} else
copy[copyIndex--] = arr[j--];
}
for (; i >= low; i--)
copy[copyIndex--] = arr[i];
for (; j > mid; j--)
copy[copyIndex--] = arr[j];
for (int k = low; k <= high; k++) {
arr[k] = copy[k];
}
}
}