Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f4319cf

Browse files
committed
merge sort
1 parent 010bf03 commit f4319cf

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

‎src/main/java/grey/algorithm/Code_0014_MergeSort.java

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,44 @@
1616

1717
public class Code_0014_MergeSort {
1818

19+
// merge sort的递归写法
20+
public static void sort(int[] arr) {
21+
mergeSort(arr, 0, arr.length - 1);
22+
}
23+
1924
// 递归解法
20-
public static void mergeSort1(int[] arr, int l, int r) {
25+
public static void mergeSort(int[] arr, int l, int r) {
2126
if (l >= r) {
2227
// 终止条件
2328
return;
2429
}
25-
int m = l + ((r - l) >> 1); // 中点位置
26-
mergeSort1(arr, l, m);
27-
mergeSort1(arr, m + 1, r);
28-
merge(arr, l, m, r);
30+
int mid = l + ((r - l) >> 1);
31+
mergeSort(arr, l, mid);
32+
mergeSort(arr, mid + 1, r);
33+
merge2(arr, l, mid, r);
34+
}
35+
36+
public static void merge2(int[] arr, int l, int m, int r) {
37+
int[] help = new int[r - l + 1];
38+
int s = l;
39+
int e = m + 1;
40+
int i = 0;
41+
while (s <= m && e <= r) {
42+
if (arr[s] <= arr[e]) {
43+
help[i++] = arr[s++];
44+
} else {
45+
help[i++] = arr[e++];
46+
}
47+
}
48+
while (s <= m) {
49+
help[i++] = arr[s++];
50+
}
51+
while (e <= r) {
52+
help[i++] = arr[e++];
53+
}
54+
for (i = 0; i < help.length; i++) {
55+
arr[l++] = help[i];
56+
}
2957
}
3058

3159
// 迭代版本的merge sort
@@ -117,7 +145,7 @@ public static void main(String[] args) {
117145
int[] copyArray1 = copyArray(arr);
118146
int[] copyArray2 = copyArray(arr);
119147
Arrays.sort(arr);
120-
mergeSort1(copyArray1, 0, copyArray1.length - 1);
148+
sort(copyArray1);
121149
mergeSort2(copyArray2, 0, copyArray2.length - 1);
122150
if (!sameValue(arr, copyArray1)) {
123151
System.out.println("出错了!");

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /