-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge sort.cpp
More file actions
78 lines (68 loc) · 1.64 KB
/
merge sort.cpp
File metadata and controls
78 lines (68 loc) · 1.64 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
#include <iostream>
using namespace std;
int max(int x, int y)
{
if(x > y)
return x;
else
return y;
}
void mergeHelp(int *input, int left, int right, int *temp)
{
if(right == left + 1)
return;
else
{
int i = 0;
int lenght = right - left;
int mid = lenght/2;
int l = left, r = left + mid;
mergeHelp(input, left, left + mid, temp);
mergeHelp(input, left + mid, right, temp);
for(i = 0; i < lenght; i++)
{
if(l < left + mid && (r == right || max(input[l], input[r]) == input[l]))
{
temp[i] = input[l];
l++;
}
else
{
temp[i] = input[r];
r++;
}
}
for(i = left; i < right; i++)
input[i] = temp[i - left];
}
}
int mergeSort(int *input, int size)
{
int *temp = new int(size*sizeof(int));
if(temp != NULL)
{
mergeHelp(input, 0, size, temp);
delete temp;
return 1;
}
else
return 0;
}
int main()
{
int N;
cout << "Number of elements: ";
cin >> N;
int array[N];
cout << "Enter the elements: " << endl;
for(int i = 0; i < N; i++)
{
cin >> array[i];
}
mergeSort(array, N);
cout << "Sorted: " << endl;
for(int i = 0; i < N; i++)
cout << array[i] << endl;
system("pause");
return 0;
}