-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort.java
88 lines (67 loc) · 1.42 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package Dsa;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MergeSort {
public static void main(String[] args) {
int[] arr = {8,3,1,4};
MergeSortFunc merge = new MergeSortFunc();
merge.mergeSort(arr, 0, arr.length-1);
System.out.println(Arrays.toString(arr));
}
}
/**
* Merge Sort Class with related functions
* @author souravwalke
*
*/
class MergeSortFunc {
/**
* Runs recursively by dividing the array, sorting and merging
* @param arr
* @param low
* @param high
*/
protected void mergeSort(int[] arr, int low, int high) {
if(low >= high) {
return;
}
int mid = (low+high)/2;
mergeSort(arr,low,mid);
mergeSort(arr,mid+1,high);
merge(arr,low,mid,high);
}
/**
* Function to sort and merge arrays
* @param arr
* @param low
* @param mid
* @param high
*/
private void merge(int[] arr, int low, int mid, int high) {
int left = low;
int right = mid+1;
List<Integer> tempList = new ArrayList<>();
while(left <= mid && right <= high) {
if(arr[left] < arr[right]) {
tempList.add(arr[left]);
left++;
}
else {
tempList.add(arr[right]);
right++;
}
}
while(left <= mid) {
tempList.add(arr[left]);
left++;
}
while(right <= high) {
tempList.add(arr[right]);
right++;
}
for (int i = low; i <= high; i++) {
arr[i] = tempList.get(i - low);
}
}
}