-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmerge.cpp
More file actions
84 lines (66 loc) · 1.23 KB
/
merge.cpp
File metadata and controls
84 lines (66 loc) · 1.23 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <bits/stdc++.h>
using namespace std;
void merge(int* arrptr, int low, int mid, int high)
{
int p=low,q=mid+1,k=0;
int tempArr[high-low+1];
cout <<"Mrg-> "<<"low: "<<low<<" mid: "<<mid<<" high: "<<high<<endl;
for(int c=low;c<=high;c++)
{
cout <<"At iteration "<<c<<", "<<"p: "<<p<<", q: "<<q<<endl;
if( p > mid)
{
tempArr[k++] = arrptr[q++];
}
else if( q > high)
{
tempArr[k++] = arrptr[p++];
}
else if( arrptr[p] < arrptr[q])
{
tempArr[k++] = arrptr[p++];
}
else
tempArr[k++] = arrptr[q++];
}
cout << "tempArr: ";
for (int i = 0; i < k; ++i)
{
arrptr[low+i] = tempArr[i];
cout << tempArr[i]<<" ";
}
cout << endl;
}
void merge_sort(int* arrptr, int low, int high)
{
if(low<high)
{
int mid = (high+low)/2;
cout<< "MS-> " <<"low: "<<low<<" mid: "<<mid<<" high: "<<high<<endl;
merge_sort(arrptr, low, mid);
merge_sort(arrptr, mid+1, high);
merge(arrptr, low, mid, high);
}
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}
int* arrptr = arr;
merge_sort(arrptr, 0, n-1);
for (int i = 0; i < n; ++i)
{
cout << arrptr[i] << " ";
}
cout << endl;
}
/*
0 1 2 3 4
0 1 2
0 1
*/