forked from arijitAD/Awesome-Algorithmic-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge.cpp
70 lines (68 loc) · 1016 Bytes
/
merge.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
66
67
68
69
70
//Code for merge sort
#include <iostream>
using namespace std;
int *tmp;
void conquer_merge(int arr[], int left, int right, int mid)
{
int k = left, i, j;
for(i = left, j=mid + 1; i<=mid && j<=right; k++)
{
if(arr[i]<=arr[j])
{
tmp[k]=arr[i];
i++;
}
else
{
tmp[k] = arr[j];
j++;
}
}
while(i <= mid)
{
tmp[k] = arr[i];
i++;
k++;
}
while(j <= right)
{
tmp[k] = arr[j];
j++;
k++;
}
for(i = left; i <= right; i++)
{
arr[i] = tmp[i];
}
}
void divi(int arr[], int left, int right)
{
if(left < right)
{
int mid = left + (right - left) / 2;
divi(arr, left, mid);
divi(arr, mid + 1, right);
conquer_merge(arr, left, right, mid);
}
}
void Merge_Sort(int arr[], int size)
{
tmp = new int[size];
divi(arr, 0, size - 1);
delete [] tmp;
}
void Print_Array(int arr[], int size)
{
for(int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
int arr[] = {2, 4, 3, 1, 6, 8, 4};
Merge_Sort(arr, 7);
Print_Array(arr, 7);
return 0;
}