public class MergeSortMain {
public static void main(String[] args) {
int[] arr = {5, 4, 6, 2, 3, 7, 9, 1, 8};
sort(arr);
print(arr);
}
static void sort(int[] arr) {
sort(arr, 0, arr.length - 1);
}
/**
* @param arr 数组
* @param leftBound 左边界
* @param rightBound 右边界
*/
static void sort(int[] arr, int leftBound, int rightBound) {
if (leftBound == rightBound) {
return;
}
// 获取右指针位置
int rightPoint = leftBound + (rightBound - leftBound) / 2;
// 左半部分排序
sort(arr, leftBound, rightPoint);
// 右半部分排序
sort(arr, rightPoint + 1, rightBound);
// 合并
merge(arr, leftBound, rightPoint + 1, rightBound);
}
/**
* @param arr 数组
* @param leftPoint 左指针
* @param rightPoint 右指针
* @param rightBound 右边界
*/
static void merge(int[] arr, int leftPoint, int rightPoint, int rightBound) {
// 创建一个临时数组
int[] temp = new int[rightBound - leftPoint + 1];
int mid = rightPoint - 1;
int i = leftPoint;
int j = rightPoint;
// 临时数组指针位置
int k = 0;
// 这样子的循环条件出现, 比如left arr都小于right arr时, left指针移动完成跳出循环, right arr并将剩余数据插入临时数组
while (i <= mid && j <= rightBound) {
// 判断左边小于右边, 则放入临时数组
if (arr[i] < arr[j]) {
temp[k] = arr[i];
k++;
i++;
} else {
temp[k] = arr[j];
k++;
j++;
}
}
while (i <= mid) {
// 左边数组指针未移动完时
temp[k] = arr[i];
k++;
i++;
}
while (j <= rightBound) {
// 右边数组指针未移动完时
temp[k] = arr[j];
k++;
j++;
}
for (int l = 0; l < temp.length; l++) {
arr[leftPoint + l] = temp[l];
}
}
static void print(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println(" ");
}
}
归并排序示例
最新推荐文章于 2022-08-23 15:16:42 发布