Skip to content

Commit 23931a3

Browse files
committed
MergeSort 归并排序
1 parent 884e86f commit 23931a3

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

src/com/gatsby/utils/SortUtil.java

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.gatsby.utils;
22

3+
import java.util.Arrays;
4+
35
/**
46
* @ClassName: SortUtil
57
* @Description: 排序类
@@ -8,13 +10,15 @@
810
*/
911

1012
public class SortUtil {
13+
static int[] tmp;
14+
1115
/**
12-
* @MethodName: quickSort
16+
* @MethodName: quickSort
1317
* @Parameter: [nums, begin, end]
1418
* @Return void
1519
* @Description: 快速排序
1620
* @author: Gatsby
17-
* @date: 2022/7/25 15:20
21+
* @date: 2022/7/25 15:20
1822
*/
1923
public static void quickSort(int[] nums, int begin, int end) {
2024
if (begin < end) {
@@ -43,6 +47,48 @@ public static void quickSort(int[] nums, int begin, int end) {
4347
quickSort(nums, j + 1, end);
4448
}
4549
}
50+
51+
52+
public static int[] mergeSort(int[] nums) {
53+
tmp = new int[nums.length];
54+
merge(nums, 0, nums.length - 1);
55+
return nums;
56+
}
57+
58+
private static void merge(int[] nums, int left, int right) {
59+
if (left >= right) return;
60+
61+
int mid = (right + left) >> 1;
62+
merge(nums, left, mid);
63+
merge(nums, mid + 1, right);
64+
65+
int i = left;
66+
// 如果数组只有一个那就不会操作了
67+
int j = mid + 1;
68+
int count = 0;
69+
while (i <= mid && j <= right) {
70+
if (nums[i] <= nums[j]) {
71+
tmp[count++] = nums[i++];
72+
} else {
73+
tmp[count++] = nums[j++];
74+
}
75+
}
76+
// System.out.println(Arrays.toString(tmp));
77+
if (i <= mid) {
78+
System.arraycopy(nums, i, tmp, count, mid - i + 1);
79+
}
80+
81+
if (j <= right) {
82+
System.arraycopy(nums, j, tmp, count, right - j + 1);
83+
}
84+
System.arraycopy(tmp, 0, nums, left, right - left + 1);
85+
}
86+
87+
public static void main(String[] args) {
88+
int[] nums = {6, 2, 5, 3, 8, 3, 1, 6, 3, 4};
89+
nums = mergeSort(nums);
90+
System.out.println(Arrays.toString(nums));
91+
}
4692
}
4793

4894

0 commit comments

Comments
 (0)