-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
36 lines (31 loc) · 904 Bytes
/
Copy pathMergeSort.cpp
File metadata and controls
36 lines (31 loc) · 904 Bytes
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
# include<iostream>
# include<vector>
using namespace std;
// O(nlogn)
void MergeSort(vector<int>& arr,int size){
vector<int> res=arr;
for(int seg=1;seg<size;seg+=seg){
for(int i=0;i<size;i+=seg+seg){
int low=i;
int k=low;
int high=(min)(i+seg+seg,size);
int mid = (min)(i+seg,size);
int start1= low, end1 = mid;
int start2= mid, end2 = high;
while(start1<end1 && start2<end2){
res[k++]=arr[start1]<arr[start2]? arr[start1++]:arr[start2++];
}
while(start1<end1) res[k++]=arr[start1++];
while(start2<end2) res[k++]=arr[start2++];
}
arr=res;
}
}
int main(){
vector<int> arr={1,2,110,2,40,482,93,40,2,20,59,99};
MergeSort(arr,arr.size());
for(int i=0;i<arr.size();i++){
cout<<arr[i]<<" ";
}
return 0;
}