-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge Sort in Array.cpp
More file actions
94 lines (74 loc) · 2.18 KB
/
Copy pathMerge Sort in Array.cpp
File metadata and controls
94 lines (74 loc) · 2.18 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
94
#include <iostream>
using namespace std;
// Function to merge two subarrays
void merge(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
// Create temporary arrays
int leftArray[n1], rightArray[n2];
// Copy data to the temporary arrays
for (int i = 0; i < n1; i++)
leftArray[i] = arr[left + i];
for (int j = 0; j < n2; j++)
rightArray[j] = arr[mid + 1 + j];
// Merge the temporary arrays back into arr[left..right]
int i = 0; // Initial index of left subarray
int j = 0; // Initial index of right subarray
int k = left; // Initial index of the merged subarray
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
arr[k] = leftArray[i];
i++;
} else {
arr[k] = rightArray[j];
j++;
}
k++;
}
// Copy the remaining elements of leftArray, if any
while (i < n1) {
arr[k] = leftArray[i];
i++;
k++;
}
// Copy the remaining elements of rightArray, if any
while (j < n2) {
arr[k] = rightArray[j];
j++;
k++;
}
}
// Function to implement Merge Sort
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
// Recursively sort the first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main() {
int size;
cout<<"Enter size: ";
cin >>size;
int arr[size];
cout<<"Enter elements of the Array:\n";
for(int i=0; i<size; i++){
cin>>arr[i];
}
// int arrSize = sizeof(arr) / sizeof(arr[0]); for static initialized array
cout << "Given array is: ";
printArray(arr, size);
mergeSort(arr, 0, size - 1);
cout << "\nSorted array is: ";
printArray(arr, size);
return 0;
}