-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
84 lines (73 loc) · 1.49 KB
/
MergeSort.java
File metadata and controls
84 lines (73 loc) · 1.49 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
import java.util.Arrays;
public class MergeSort {
public static int[] mergeSort(int[] arry,int start, int end){
if(start > end){
if(start > arry.length-1){
return null;
}
int[] tmp = {arry[start]};
return tmp;
}
int mid = (start+end)/2;
int[] left = mergeSort(arry,start,mid-1);
int [] right = mergeSort(arry,mid+1,end);
return merge(left,right);
}
public static int[] merge(int[] a, int[] b){
if(a==null||b==null) return a==null?b:a;
int[] tmp = new int[a.length+b.length];
int alen = a.length-1;
int blen = b.length-1;
int cur = 0;
int acur = 0;
int bcur = 0;
if(a[0]>b[blen]){
for(int i=0;i<b.length;i++){
tmp[i] = b[i];
}
int index = 0;
for(int j=b.length;j<tmp.length;j++){
tmp[j] = a[index];
index++;
}
}else if(b[0]>a[alen]){
for(int i=0;i<a.length;i++){
tmp[i] = a[i];
}
int index=0;
for(int j=a.length;j<tmp.length;j++){
tmp[j] = b[index];
index++;
}
}else{
while( cur < tmp.length){
if(acur>alen){
tmp[cur] = b[bcur];
cur++;
bcur++;
continue;
}
if(bcur>blen){
tmp[cur] = a[acur];
cur++;
acur++;
continue;
}
if(a[acur]<=b[bcur]){
tmp[cur] = a[acur];
acur++;
cur++;
}else{
tmp[cur] = b[bcur];
bcur++;
cur++;
}
}
}
return tmp;
}
public static void main(String args[]){
int[] a = {7,5,3,2,1,6,9};
System.out.println(Arrays.toString(mergeSort(a,0,a.length-1)));
}
}