-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_sort.cpp
More file actions
77 lines (64 loc) · 1.68 KB
/
merge_sort.cpp
File metadata and controls
77 lines (64 loc) · 1.68 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
#include <stdio.h>
// Merge function to merge two sorted subarrays
void merge(int arr[], int low, int mid, int high) {
int n1 = mid - low + 1; // Size of left subarray
int n2 = high - mid; // Size of right subarray
int left[n1], right[n2]; // Temporary arrays
// Copy data to temporary arrays left[] and right[]
for (int i = 0; i < n1; i++) {
left[i] = arr[low + i];
}
for (int i = 0; i < n2; i++) {
right[i] = arr[mid + 1 + i];
}
// Merge the temporary arrays back into arr[low..high]
int i = 0, j = 0, k = low;
while (i < n1 && j < n2) {
if (left[i] <= right[j]) {
arr[k] = left[i];
i++;
} else {
arr[k] = right[j];
j++;
}
k++;
}
// Copy the remaining elements of left[] and right[] if any
while (i < n1) {
arr[k] = left[i];
i++;
k++;
}
while (j < n2) {
arr[k] = right[j];
j++;
k++;
}
}
// Merge sort function
void merge_sort(int arr[], int low, int high) {
if (low < high) {
int mid = low + (high - low) / 2;
// Recursively sort the two halves
merge_sort(arr, low, mid);
merge_sort(arr, mid + 1, high);
// Merge the sorted halves
merge(arr, low, mid, high);
}
}
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
printf("Enter array elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
merge_sort(a, 0, n - 1);
printf("Sorted array elements:\n");
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
return 0;
}