-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_Sort-ARRAY.cpp
More file actions
64 lines (54 loc) · 1.61 KB
/
Copy pathMerge_Sort-ARRAY.cpp
File metadata and controls
64 lines (54 loc) · 1.61 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
#include <bits/stdc++.h>
using namespace std;
// Time Complexity = O(n * log(n)) in all cases.
// Space Complexity = O(n).
void mergeAlgo(int *a, int startIndex, int midIndex, int endIndex)
{
int n = endIndex - startIndex + 1;
// Helping array to temporarily store sorted results.
int helper[n];
// i represents starting index of first half of the array.
// j represents starting index of second half of the array.
// k represents starting index of helper array.
int i = startIndex;
int j = midIndex + 1;
int k = 0;
while (i <= midIndex and j <= endIndex)
{
if (a[i] <= a[j])
helper[k++] = a[i++];
else
helper[k++] = a[j++];
}
// Merging elements left to be merged.
while (i <= midIndex)
helper[k++] = a[i++];
while (j <= endIndex)
helper[k++] = a[j++];
// Copying back the elements to the original array.
for (int i = startIndex; i <= endIndex; i++)
a[i] = helper[i - startIndex];
}
void mergeSort(int *a, int startIndex, int endIndex)
{
if (startIndex < endIndex)
{
int midIndex = startIndex + (endIndex - startIndex) / 2;
// Divide
mergeSort(a, startIndex, midIndex);
mergeSort(a, midIndex + 1, endIndex);
// Conquer
mergeAlgo(a, startIndex, midIndex, endIndex);
}
}
int main()
{
int a[] = {3, 5, 1, 2, 4};
int n = sizeof(a) / sizeof(a[0]);
int startIndex = 0, endIndex = n - 1;
mergeSort(a, startIndex, endIndex);
// Printing the sorted array.
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
}