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 8038332

Browse files
committed
添加归并排序实现
1 parent eeedc83 commit 8038332

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed
Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.mistray.merge;
22

3+
import java.util.Arrays;
4+
35
/**
46
* @author MistRay
57
* @create 2018年11月20日
@@ -8,10 +10,47 @@
810
public class MergeSort {
911

1012
public static void main(String[] args) {
13+
int[] array = { 35, 24, 86, 12, 95, 58, 35, 42, 21, 73 };
14+
sort(array, 0, array.length - 1);
15+
System.out.println(Arrays.toString(array));
16+
}
17+
18+
public static void sort(int[] array, int start, int end){
19+
if (start >= end){
20+
return;
21+
}
1122

23+
int mid = (start + end) >> 1;
24+
// 递归实现归并排序
25+
sort(array, start, mid);
26+
sort(array, mid + 1, end);
27+
mergerSort(array, start, mid, end);
1228
}
1329

14-
public static void mergeSort(){
30+
// 将两个有序序列归并为一个有序序列(二路归并)
31+
private static void mergerSort(int[] array, int start, int mid, int end) {
32+
int[] arr = new int[end + 1]; // 定义一个临时数组,用来存储排序后的结果
33+
int low = start; // 临时数组的索引
34+
int left = start;
35+
36+
int center = mid + 1;
37+
// 取出最小值放入临时数组中
38+
while (start <= mid && center <= end) {
39+
arr[low++] = array[start] > array[center] ? array[center++] : array[start++];
40+
}
41+
42+
// 若还有段序列不为空,则将其加入临时数组末尾
43+
44+
while (start <= mid) {
45+
arr[low++] = array[start++];
46+
}
47+
while (center <= end) {
48+
arr[low++] = array[center++];
49+
}
1550

51+
// 将临时数组中的值copy到原数组中
52+
for (int i = left; i <= end; i++) {
53+
array[i] = arr[i];
54+
}
1655
}
1756
}

0 commit comments

Comments
(0)

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