- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.java
More file actions
Latest commit
60 lines (48 loc) · 1.18 KB
/
Copy pathmergeSort.java
File metadata and controls
60 lines (48 loc) · 1.18 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
packageyoozoo.day1;
publicclassTest9 {
publicstaticvoidmain(String[] args) {
// 归并排序
int[] arr = {1,4,2,8,12,9};
intlow = 0;
inthigh = arr.length-1;
int[] res = newint[arr.length];
mSort(arr , res , low ,high);
for(intt = 0 ;t < res.length ; t++){
System.out.println(res[t]);
}
}
privatestaticvoidmSort(int[] arr, int[] res, intlow, inthigh) {
intm; //将数组二等分坐标
int[] tR2 = newint[arr.length]; //临时数组
if(low == high){
res[low] = arr[low];
}else{
m = (low + high)/2;
mSort(arr, tR2, low, m);
mSort(arr, tR2, m+1, high);
merge(tR2, res , low , m , high); //把临时数组值合并到结果数组中
}
}
//这是一个合并的过程
privatestaticvoidmerge(int[] tR2, int[] res, intlow, intm, inthigh) {
intj,k,l;
for(j=m+1,k=low; low<=m&&j<=high; k++) {
if(tR2[low] < tR2[j]){
res[k] = tR2[low++];
}else{
res[k] = tR2[j++];
}
}
//把左边的剩余数全部都移动到结果数组中
if(low <= m){
for(l=0;l <= m-low;l++){
res[k+l] = tR2[low+l];
}
}
if(j <= high){
for(l=0; l<= high-j;l++){
res[k+l] = tR2[j+l];
}
}
}
}