-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge sort
59 lines (58 loc) · 1.29 KB
/
Merge sort
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
void merge(int arr[], int l, int m, int r)
{
// Your code here
int res[r - l + 1] ;
int a = l ;
int b = m + 1 ;
int ind = 0 ;
while(a < m + 1 && b < r + 1)
{
if(arr[a] < arr[b])
{
res[ind] = arr[a] ;
a++ ;
ind++;
}
else
{
res[ind] = arr[b] ;
b++ ;
ind++ ;
}
}
if( a < m + 1)
{
while( a < m + 1)
{
res[ind] = arr[a] ;
a++ ;
ind++ ;
}
}
else
{
while(b < r + 1)
{
res[ind] = arr[b] ;
b++ ;
ind++ ;
}
}
int k,i ;
for(k=0, i=l; k< r-l + 1; k++, i++) {
arr[i] = res[k];
}
}
public:
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) ;
}