forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge_sort.cpp
98 lines (80 loc) · 2.64 KB
/
Merge_sort.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
using namespace std;
// Function to print the array.
void printArray(int * arr, int length) {
for (int i = 0; i < length; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// Function to merge the sub-arrays.
void merge(int * arr, int low, int mid, int high) {
int i, j, k;
int lengthLeft = mid - low + 1;
int lengthRight = high - mid;
// Creating two temp arrays to store left and right sub-arrays.
int arrLeft[lengthLeft], arrRight[lengthRight];
// Copying the data from the actual array to left and right temp arrays.
for (int a = 0; a < lengthLeft; a++) {
arrLeft[a] = arr[low + a];
}
for (int a = 0; a < lengthRight; a++) {
arrRight[a] = arr[mid + 1 + a];
}
// Merging the temp arrays back into the actual array.
i = 0; // Starting index of arrLeft[].
j = 0; // Staring index of arrRight[].
k = low; // Starting index of merged subarray.
while (i < lengthLeft && j < lengthRight) {
// Checking and placing the smaller number of both temp arrays into the main array.
if (arrLeft[i] <= arrRight[j]) {
arr[k] = arrLeft[i];
i++;
} else {
arr[k] = arrRight[j];
j++;
}
k++;
}
// After the successful execution of the above loop
// copying the remaining elements of the left subarray (if remaining).
while (i < lengthLeft) {
arr[k] = arrLeft[i];
k++;
i++;
}
// Copying the remaining elements of the right sub array (if remaining).
while (j < lengthRight) {
arr[k] = arrRight[j];
k++;
j++;
}
}
// The mergeSort() function.
void mergeSort(int * arr, int low, int high) {
int mid;
if (low < high) {
// Calculating the mid.
mid = (low + high) / 2;
// Calling the function mergeSort() recursively and breaking down the given array into smaller sub arrays.
mergeSort(arr, low, mid);
mergeSort(arr, mid + 1, high);
// Calling the merge() function to merge the sorted subarrays into the main array.
merge(arr, low, mid, high);
}
}
int main() {
// Initialzing the array.
int arr[] = {9, 14, 4, 6, 5, 8, 7};
// Calculating the length of the array.
int length = sizeof(arr) / sizeof(int);
// Printing the array before sorting.
cout << "Array, before calling the mergeSort() : ";
printArray(arr, length);
// Calling the mergeSort() function.
mergeSort(arr, 0, length - 1);
// Printing the array after sorting.
cout << "Array, after calling the mergeSort() : ";
printArray(arr, length);
return 0;
}