import java.awt.print.PrinterGraphics;
/**
* 排序--归并排序
* 先使子序列有序,在合并得到完全有序
*/
public class MergeSort {
// 递归方法
public static void mergeSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
process(arr, 0, arr.length - 1);
}
public static void process(int[] arr, int left, int right) {
if (left == right) {
return;
}
int mid = left + ((right - left) >> 1);
//使左子序列有序
process(arr, left, mid);
//使得右子序列有序
process(arr, mid + 1, right);
merge(arr, left, mid, right);
}
//使得arr 有序
public static void merge(int[] arr, int left, int mid, int right) {
//辅助数组
int[] temp = new int[right - left + 1];
int i = 0;
int p1 = left;
int p2 = mid + 1;
while (p1 <= mid && p2 <= right) {
/*if (arr[p1] < arr[p2]){
temp[i] = arr[p1];
p1++;
}else {
temp[i] = arr[p2];
p2++;
}
i++;*/
temp[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
}
while (p1 <= mid) {
temp[i++] = arr[p1++];
}
while (p2 <= right) {
temp[i++] = arr[p2++];
}
for (int j = 0; j < temp.length; j++) {
arr[left + j] = temp[j];
}
}
public static void main(String[] args){
int[] arr = new int[]{1,23,3,42,3,21,23,1,34,53,23,42,4,23,23,432,34,2,12,44};
mergeSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+",");
}
System.out.println();
}
}
排序--归并排序
最新推荐文章于 2024-08-16 23:08:28 发布