-
Notifications
You must be signed in to change notification settings - Fork 24
/
merge_sort.cpp
52 lines (46 loc) · 924 Bytes
/
merge_sort.cpp
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
#include<bits/stdc++.h>
using namespace std;
void merge(vector<int> &arr, int l, int m, int r) {
int nl = m-l+1;
int nr = r-m;
vector<int> larr(nl);
vector<int> rarr(nr);
for(int i=0; i<nl; i++) larr[i] = arr[l+i];
for(int j=0; j<nr; j++) rarr[j] = arr[m+1+j];
int i=0, j=0, k=l;
while(i < nl && j < nr) {
if(larr[i] <= rarr[j]) {
arr[k] = larr[i];
i++;
}else{
arr[k] = rarr[j];
j++;
}
k++;
}
while(i<nl) {
arr[k] = larr[i];
i++; k++;
}
while(j<nr) {
arr[k] = rarr[j];
j++; k++;
}
}
void mergeSort(vector<int> &arr, int l, int r) {
int m;
if(l < r) {
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
int main() {
vector<int> arr = {-10, 9, 0, 3, 4, -7};
mergeSort(arr, 0, 5);
for(int i:arr) {
cout << i << " ";
}
cout << endl;
}