-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.cpp
More file actions
87 lines (69 loc) · 1.44 KB
/
mergeSort.cpp
File metadata and controls
87 lines (69 loc) · 1.44 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
85
86
87
#include <iostream>
using namespace std;
void mergeArray(int *arr, int s, int e, int mid)
{
int len1 = mid - s + 1;
int len2 = e - mid;
// Created two new Array
int *first = new int[len1];
int *second = new int[len2];
int startIndex = s;
for (int i = 0; i < len1; i++)
{
first[i] = arr[startIndex];
startIndex++;
}
startIndex = mid + 1;
for (int i = 0; i < len2; i++)
{
second[i] = arr[startIndex];
startIndex++;
}
// Merge Two sorted Arrays
int i = 0;
int j = 0;
startIndex = s;
while (i < len1 && j < len2)
{
if (first[i] < second[j])
{
arr[startIndex++] = first[i++];
}
else if (second[j] < first[i])
{
arr[startIndex++] = second[j++];
}
}
while (i < len1)
{
arr[startIndex++] = first[i++];
}
while (j < len2)
{
arr[startIndex++] = second[j++];
}
delete[] first;
delete[] second;
}
void mergSort(int *arr, int s, int e)
{
// Base Case
if (s >= e)
return;
int mid = s + (e - s) / 2;
// Left Part Sorted
mergSort(arr, 0, mid);
// Right Part Sorted
mergSort(arr, mid + 1, e);
mergeArray(arr, s, e, mid);
}
int main()
{
int arr[7]{38, 26, 43, 3, 9, 82, 10};
int n = 7;
mergSort(arr, 0, n - 1);
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}