Skip to content

Commit 775bcbe

Browse files
committed
完善归并算法
1 parent 8df81de commit 775bcbe

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

src/org/algorithm/array/sort/client/SortClient.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public class SortClient {
88

99
public static void main(String[] args) {
1010
int[] array = {34, 23, 76, 56, 54, 12, 34, 65, 45, 9, 8, 7, 6, 5};
11-
// int[] array = {10, 9, 8, 7, 6};
11+
// int[] array = {13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
1212
Sortable sortable = new MergeSort();
1313
array = sortable.sort(array);
1414

src/org/algorithm/array/sort/impl/MergeSort.java

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,34 @@ public int[] sort(int[] array) {
2525
return array;
2626
}
2727

28+
// 对数组进行分组的核心模块
2829
private void sortCore(int[] array) {
2930
int length = array.length;
30-
merge(array, 0, length / 2, length - 1);
31+
32+
int groupSize = 1;
33+
while(groupSize < length) {
34+
for (int i = 0; i < length; i += (groupSize * 2)) {
35+
int low = i;
36+
int hight = Math.min(i + groupSize * 2 - 1, length - 1);
37+
merge(array, low, low + groupSize - 1, hight);
38+
}
39+
groupSize *= 2;
40+
}
41+
42+
// 对分组中的奇数情况进行另外处理
43+
if (groupSize / 2 < length) {
44+
int low = 0;
45+
int hight = length - 1;
46+
merge(array, low, groupSize / 2 - 1, hight);
47+
}
3148
}
3249

33-
// 合并的核心算法
50+
// 合并的核心模块
3451
private void merge(int[] array, int low, int mid, int hight) {
52+
if (low >= hight) {
53+
return;
54+
}
55+
3556
int[] auxArray = new int[hight - low + 1];
3657
int index1 = low;
3758
int index2 = mid + 1;
@@ -49,14 +70,21 @@ private void merge(int[] array, int low, int mid, int hight) {
4970
}
5071
}
5172

73+
// 继续合并前半段数组中未被合并的部分
5274
while (index1 <= mid) {
53-
auxArray[i++] = array[index1];
75+
auxArray[i] = array[index1];
76+
index1++;
77+
i++;
5478
}
5579

80+
// 继续合并后半段数组中未被合并的部分
5681
while (index2 <= hight) {
57-
auxArray[i++] = array[index2];
82+
auxArray[i] = array[index2];
83+
index2++;
84+
i++;
5885
}
5986

87+
// 将合并好的序列写回到数组中
6088
for (int j = 0; j < auxArray.length; j++) {
6189
array[low + j] = auxArray[j];
6290
}

0 commit comments

Comments
 (0)