-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
66 lines (48 loc) · 1.01 KB
/
MergeSort.java
File metadata and controls
66 lines (48 loc) · 1.01 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
package geeks.algo.sort;
public class MergeSort extends Sort{
MergeSort(int[] arr) {
super(arr);
}
@Override
protected void performSort() {
int[] arr= this.arr;
int n = arr.length;
mergeSort(arr, 0, n-1);
}
private void mergeSort(int[] arr, int low, int high){
if(low<high){
int middle = low+ (high-low)/2;
mergeSort(arr, low, middle);
mergeSort(arr, middle+1, high);
merge(arr, low, middle, high);
}
}
private void merge(int[] arr, int low, int middle, int high) {
int[] tmp = new int[arr.length];
for(int i=low;i<=high; i++){
tmp[i] = arr[i];
}
int i=low;
int j=middle+1;
int k=low;
while(i<=middle && j<=high){
if(tmp[i]<tmp[j]){
arr[k++]=tmp[i++];
}else{
arr[k++]=tmp[j++];
}
}
while(i<=middle){
arr[k++]=tmp[i++];
}
while(j<=high){
arr[k++]=tmp[j++];
}
}
@Override
protected void setComplexities() {
this.timeComplexity="O(n * Log(n))";
this.spaceComplexity="O(n)";
this.type="Merge Sort";
}
}