-
Notifications
You must be signed in to change notification settings - Fork 10
/
merge-sort.cpp
65 lines (47 loc) · 1.04 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<bits/stdc++.h>
using namespace std;
void merge(vector<int>&A,int left,int mid,int right){
int i=left,j=mid+1,k=0;
int temp[right-left+1];
x`
while(i<=mid && j<=right){
if(A[i] <= A[j]){
temp[k++] = A[i++];
}else {
temp[k++] = A[j++];
}
}
while(i<=mid){
temp[k++] = A[i++];
}
while(j<=right){
temp[k++] = A[j++];
}
for(int i=left,k=0;i<=right;i++,k++){
A[i] = temp[k];
}
}
void merge_sort(vector<int> &A,int left,int right){
if (left>=right)
return;
int mid = (left + right)/2;
merge_sort(A,left,mid);
merge_sort(A,mid+1,right);
merge(A,left,mid,right);
}
void printarray(vector<int>&A,int n){
for (int i=0;i<n;i++){
cout<<A[i]<<" ";
}
}
int main(){
vector<int>A;
A.push_back(5);
A.push_back(4);
A.push_back(3);
A.push_back(2);
A.push_back(1);
merge_sort(A,0,4);
printarray(A,5);
return 0;
}