归并排序算法
归并排序是建立在归并操作上的一种有效的排序算法,该算法是采用分治法的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。将两个有序表合并成一个有序表。归并排序是一种稳定的排序方法。
import java.util.Arrays;
/**
* 描述:归并排序
*/
public class MergeSort {
public static void main(String[] args) {
int[] arr = new int[]{6, 8, 3, 4, 1, 9, 0, 12, 7, 5};
System.out.println(Arrays.toString(arr));
mergeSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
private static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
private static void merge(int[] arr, int left, int mid, int right) {
int[] tmp = new int[arr.length];
int tm1 = left;
int rights = mid + 1;
int i = left;
while (left <= mid && rights <= right) {
if (arr[left] <= arr[rights]) {
tmp[i++] = arr[left++];
} else {
tmp[i++] = arr[rights++];
}
}
while (left <= mid) {
tmp[i++] = arr[left++];
}
while (rights <= right) {
tmp[i++] = arr[rights++];
}
while (tm1 <=right) {
arr[tm1] = tmp[tm1];
tm1++;
}
}
}