TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
merge_sort.cpp
Go to the documentation of this file.
1
16#include <iostream>
17
33void merge(int *arr, int l, int m, int r) {
34 int i, j, k;
35 int n1 = m - l + 1;
36 int n2 = r - m;
37
38 int *L = new int[n1], *R = new int[n2];
39
40 for (i = 0; i < n1; i++) L[i] = arr[l + i];
41 for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j];
42
43 i = 0;
44 j = 0;
45 k = l;
46 while (i < n1 || j < n2) {
47 if (j >= n2 || (i < n1 && L[i] <= R[j])) {
48 arr[k] = L[i];
49 i++;
50 } else {
51 arr[k] = R[j];
52 j++;
53 }
54 k++;
55 }
56
57 delete[] L;
58 delete[] R;
59}
60
71void mergeSort(int *arr, int l, int r) {
72 if (l < r) {
73 int m = l + (r - l) / 2;
74 mergeSort(arr, l, m);
75 mergeSort(arr, m + 1, r);
76 merge(arr, l, m, r);
77 }
78}
79
84void show(int *arr, int size) {
85 for (int i = 0; i < size; i++) std::cout << arr[i] << " ";
86 std::cout << "\n";
87}
88
90int main() {
91 int size;
92 std::cout << "Enter the number of elements : ";
93 std::cin >> size;
94 int *arr = new int[size];
95 std::cout << "Enter the unsorted elements : ";
96 for (int i = 0; i < size; ++i) {
97 std::cin >> arr[i];
98 }
99 mergeSort(arr, 0, size - 1);
100 std::cout << "Sorted array : ";
101 show(arr, size);
102 delete[] arr;
103 return 0;
104}
void merge(int *arr, int l, int m, int r)
void mergeSort(int *arr, int l, int r)
int main()