-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergesort.cpp
More file actions
93 lines (76 loc) · 2.35 KB
/
mergesort.cpp
File metadata and controls
93 lines (76 loc) · 2.35 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
88
89
90
91
92
93
#include <iostream>
#include <vector>
using namespace std;
// Class for Merge Sort
class MergeSort {
public:
// Function to merge two sorted subarrays into one sorted array
void merge(vector<int>& arr, int left, int mid, int right) {
int n1 = mid - left + 1; // Size of the left subarray
int n2 = right - mid; // Size of the right subarray
// Temporary arrays for the left and right subarrays
vector<int> leftArr(n1), rightArr(n2);
// Copy data into temporary arrays
for (int i = 0; i < n1; i++) {
leftArr[i] = arr[left + i];
}
for (int i = 0; i < n2; i++) {
rightArr[i] = arr[mid + 1 + i];
}
// Merge the two subarrays back into the original array
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k++] = leftArr[i++];
} else {
arr[k++] = rightArr[j++];
}
}
// Copy remaining elements from leftArr, if any
while (i < n1) {
arr[k++] = leftArr[i++];
}
// Copy remaining elements from rightArr, if any
while (j < n2) {
arr[k++] = rightArr[j++];
}
}
// Merge sort function to recursively divide the array
void mergeSort(vector<int>& arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
// Recursively sort the two halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the two sorted halves
merge(arr, left, mid, right);
}
}
// Function to print the array
void printArray(const vector<int>& arr) {
for (int num : arr) {
cout << num << " ";
}
cout << endl;
}
};
int main() {
int n;
// Input the size of the array
cout << "Enter the size of the array: ";
cin >> n;
// Input array elements
vector<int> arr(n);
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
// Create an object of the MergeSort class
MergeSort ms;
// Perform merge sort
ms.mergeSort(arr, 0, n - 1);
// Print the sorted array
cout << "Sorted array: ";
ms.printArray(arr);
return 0;
}