归并排序
主要采用递归思想和双指针法
package com.zhou.ObjectStream;
public class GuiBinPaiXu {
public static void main(String[] args) {
int[] a = {4, 2, 43, 23, 1, 6, 8};
int left = 0;
int right = a.length - 1;
proSort(a, left, right);
for (int i : a) {
System.out.print(i+" ");
}
}
public static void proSort(int a[], int left, int right) {
if (left == right) { //当只有一个值时,结束
return;
}
int mid = left + (right - left) / 2; //防止(left+right)导致数据溢出
proSort(a, left, mid); //递归划分左侧数据
proSort(a, mid + 1, right); //递归划分右侧数据
merge(a, left, mid, right); //合并左侧和右侧数据
}
public static void merge(int a[], int left, int mid, int right) {
int[] arr = new int[right - left + 1]; //开辟一个新数组,用来存放排序好的数据
int i = 0;
int p1 = left;
int p2 = mid + 1;
while (p1 <= mid && p2 <= right) { //在左侧和右侧开头分别设置一个指针,比较大小,谁大,谁先放在新数组中
arr[i++] = a[p1] > a[p2] ? a[p2++] : a[p1++];
}
while (p1 <= mid) { //把某侧剩余数据放入新数组中
arr[i++] = a[p1++];
}
while (p2 <= right) {
arr[i++] = a[p2++];
}
for (int j = 0; j < arr.length; j++) { //把新数组数据赋给原来数组
a[left + j] = arr[j];
}
}
}