|
1 | 1 | package com.gatsby.utils;
|
2 | 2 |
|
| 3 | +import java.util.Arrays; |
| 4 | + |
3 | 5 | /**
|
4 | 6 | * @ClassName: SortUtil
|
5 | 7 | * @Description: 排序类
|
|
8 | 10 | */
|
9 | 11 |
|
10 | 12 | public class SortUtil {
|
| 13 | + static int[] tmp; |
| 14 | + |
11 | 15 | /**
|
12 |
| - * @MethodName: quickSort |
| 16 | + * @MethodName: quickSort |
13 | 17 | * @Parameter: [nums, begin, end]
|
14 | 18 | * @Return void
|
15 | 19 | * @Description: 快速排序
|
16 | 20 | * @author: Gatsby
|
17 |
| - * @date: 2022/7/25 15:20 |
| 21 | + * @date: 2022/7/25 15:20 |
18 | 22 | */
|
19 | 23 | public static void quickSort(int[] nums, int begin, int end) {
|
20 | 24 | if (begin < end) {
|
@@ -43,6 +47,48 @@ public static void quickSort(int[] nums, int begin, int end) {
|
43 | 47 | quickSort(nums, j + 1, end);
|
44 | 48 | }
|
45 | 49 | }
|
| 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 | + } |
46 | 92 | }
|
47 | 93 |
|
48 | 94 |
|
0 commit comments