-
Notifications
You must be signed in to change notification settings - Fork 692
/
MergeSort.java
64 lines (50 loc) · 1.85 KB
/
MergeSort.java
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
package sort;
import java.util.Arrays;
public class MergeSort {
/*
* Merge sort uses divide & conquer method by splitting the array into smaller parts until there is only one element.
* The elements are then compared and sorted and merged.
* Split the arr into half by finding the median.
* Call mergeSort on the first half and mergeSort on the second half. Then merge the two halves.
* The time complexity of merge sort is always O(n log n): in all 3 cases (worst, average and best) as merge sort
* always divides the array in two halves and take linear time to merge two halves.
* */
public static int[] mergeSort(int[] arr, int lowerIndex, int upperIndex) {
if(arr.length == 1) return arr;
if(lowerIndex >= upperIndex) return arr;
int median = (lowerIndex + upperIndex)/2;
mergeSort(arr, lowerIndex, median);
mergeSort(arr, median+1, upperIndex);
merge(arr, lowerIndex, median, upperIndex);
return arr;
}
public static int[] merge(int[]arr, int lowerIndex, int median, int upperIndex) {
int[] tempArr = new int[arr.length];
for(int i=0; i<= upperIndex; i++) {
tempArr[i] = arr[i];
}
int i = lowerIndex;
int j = median+1;
int k = lowerIndex;
while (i <= median && j<= upperIndex) {
if(tempArr[i] < tempArr[j]) {
arr[k] = tempArr[i];
i++;
} else {
arr[k] = tempArr[j];
j++;
}
k++;
}
while (i<= median) {
arr[k] = tempArr[i];
i++;
k++;
}
return arr;
}
public static void main(String[] args) {
int[] arr = {55, 23, 26, 2, 25};
System.out.print(Arrays.toString(mergeSort(arr, 0, arr.length-1)));
}
}