-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerge Sort.java
41 lines (40 loc) · 889 Bytes
/
Merge Sort.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
class Solution
{
void merge(int arr[], int l, int m, int r)
{
// Your code here
int lt=l,rt=m+1;
ArrayList<Integer> ans=new ArrayList<>();
while(lt<=m && rt<=r){
if(arr[lt]<=arr[rt]){
ans.add(arr[lt]);
lt++;
}
else{
ans.add(arr[rt]);
rt++;
}
}
while(lt<=m){
ans.add(arr[lt]);
lt++;
}
while(rt<=r){
ans.add(arr[rt]);
rt++;
}
for(int i=l;i<=r;i++){
arr[i]=ans.get(i-l);
}
//return;
}
void mergeSort(int arr[], int l, int r)
{
//code here
if(l==r)return;
int mid=(l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,mid,r);
}
}