-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
105 lines (77 loc) · 2.34 KB
/
MergeSort.java
File metadata and controls
105 lines (77 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package algorithm.sort;
import java.util.Random;
/**
* <p>
* Merge Sort is a Divide and Conquer sorting algorithm.
* </p>
*
* Divide Step :
* Divide the current array into two halves and then recursively sort the two halves.
*
* Conquer Step :
* Merge the two (sorted) halves to form a sorted array.
*/
public class MergeSort {
public static void main(String[] args) {
int problemSize = 15;
final Random random = new Random();
// int[] data = new int[]{29,62,28,78,83,91,96,64,27,64};
int[] data = new int[problemSize];
for(int i = 0; i < problemSize; i ++) {
data[i] = random.nextInt(150);
System.out.println(data[i]);
}
mergeSort(data, 0, data.length - 1);
System.out.println(" -- Sorted --");
for(int i = 0; i < problemSize; i ++) {
System.out.println(data[i]);
}
}
/**
*
*
* @param array
* @param low
* @param high
*/
public static void mergeSort(int array[], int low, int high) {
if (low < high) { // 结束条件,分解到只有一个元素
int mid = (low+high) / 2;
mergeSort(array, low , mid ); // divide into two halves
mergeSort(array, mid+1, high); // then recursively sort them
merge(array, low, mid, high); // conquer: the merge routine
}
}
/**
* 原地合并数组的左右两部分。
* 循环遍历两个部分,通过比较head元素,实现合并。
* 代码中依赖copy空间来临时存放排序后的结果。
* @param array
* @param low
* @param mid
* @param high
*/
public static void merge(int[] array, int low, int mid, int high) {
int n = high - low + 1;
int leftHead = low;
int rightHead = mid + 1;
int[] copy = new int[n];
int idx = 0;
while( leftHead <= mid && rightHead <= high ) {
if( array[leftHead] <= array[rightHead]) {
copy[idx++] = array[leftHead++];
} else {
copy[idx++] = array[rightHead++];
}
}
while(leftHead <= mid) {
copy[idx++] = array[leftHead++];
}
while(rightHead <= high) {
copy[idx++] = array[rightHead++];
}
for(int k = 0; k < n; k++) {
array[low + k] = copy[k];
}
}
}