Skip to content

Commit 5a4753d

Browse files
committed
添加归并排序
1 parent e75fd0e commit 5a4753d

2 files changed

Lines changed: 61 additions & 2 deletions

File tree

src/main/java/cn/byhieg/algorithmtutorial/Sort.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,59 @@ public void bubbleSort2(int[] nums) {
128128
}
129129
}
130130

131+
/**
132+
* 归并排序,将数组一分为二,对于每一子数组继续进行上述步骤,直到子数组只有1个元素,那么自然是有序的。
133+
* 然后不断合并两个数组,直到合并到整个数组。
134+
* 时间复杂度o(NlgN)
135+
* 空间复杂度o(N)
136+
* @param nums
137+
*/
138+
public void mergeSort(int[] nums) {
139+
int length = nums.length;
140+
int low = 0;
141+
int high = length - 1;
142+
realSort(nums, low, high);
143+
}
144+
145+
/**
146+
* 归并排序真正的sort函数
147+
* @param nums 待排序的数组
148+
* @param low 最低位
149+
* @param high 最高位
150+
*/
151+
private void realSort(int[] nums, int low, int high) {
152+
int mid = (low + high) / 2;
153+
if (low < high) {
154+
realSort(nums, low, mid);
155+
realSort(nums, mid + 1, high);
156+
realMerge(nums, low, mid, high);
157+
}
158+
}
159+
160+
private void realMerge(int[] nums, int low, int mid, int high) {
161+
int[] tmpNums = new int[high - low + 1];
162+
int leftPoint = low;
163+
int rightPoint = mid + 1;
164+
int index = 0;
165+
166+
while (leftPoint <= mid && rightPoint <= high) {
167+
if (nums[leftPoint] < nums[rightPoint]) {
168+
tmpNums[index++] = nums[leftPoint++];
169+
}else{
170+
tmpNums[index++] = nums[rightPoint++];
171+
}
172+
}
173+
174+
while (leftPoint <= mid) {
175+
tmpNums[index++] = nums[leftPoint++];
176+
}
177+
while (rightPoint <= high) {
178+
tmpNums[index++] = nums[rightPoint++];
179+
}
180+
181+
System.arraycopy(tmpNums, 0, nums, low, tmpNums.length);
182+
}
183+
131184
/**
132185
* 快速排序,选定一个切分元素,每一轮排序后,都保证切分元素之前的元素都小于切分元素,切分元素之后的元素都大于切分元素
133186
* 时间复杂度o(NlgN)
@@ -263,4 +316,5 @@ public void sink(int [] nums, int i,int n) {
263316
}
264317

265318

319+
266320
}

src/test/java/cn/byhieg/algorithmtutorialtest/SortTest.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,13 @@ public void tearDown() throws Exception {
4141
// new Sort().quickSort(nums);
4242
// }
4343

44-
public void testHeapSort() throws Exception {
45-
new Sort().heapSort(nums);
44+
// public void testHeapSort() throws Exception {
45+
// new Sort().heapSort(nums);
46+
// }
47+
48+
public void testMergeSort() throws Exception {
49+
new Sort().mergeSort(nums);
50+
4651
}
4752

4853
}

0 commit comments

Comments
 (0)