-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge.cpp
54 lines (53 loc) · 1.09 KB
/
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
#include <iostream>
using namespace std;
void merge(int *arr, int low, int high, int mid)
{
int i, j, k, c[50];
i = low;
k = low;
j = mid + 1;
while (i <= mid && j <= high) {
if (arr[i] < arr[j]) {
c[k++] = arr[i++];
}
else {
c[k++] = arr[j++];
}
}
while (i <= mid) {
c[k++] = arr[i++];
}
while (j <= high) {
c[k++] = arr[j++];
}
for (i = low; i < k; i++) {
arr[i] = c[i];
}
}
void merge_sort(int *arr, int low, int high)
{
int mid;
if (low < high){
mid=(low+high)/2;
merge_sort(arr,low,mid);
merge_sort(arr,mid+1,high);
merge(arr,low,high,mid);
}
}
int main()
{
int myarray[30], num;
cout<<"Enter the size : \n";
cin>>num;
cout<<"Enter array element : \n";
for (int i = 0; i < num; i++) {
cin>>myarray[i];
}
merge_sort(myarray, 0, num-1);
cout<<"Sorted array is\n";
for (int i = 0; i < num; i++)
{
cout<<myarray[i]<<" ";
}
return 0;
}