1#include <iostream>
2using namespace std;
3
4
5void merge(int arr[], int l, int m, int r)
6{
7 int n1 = m - l + 1;
8 int n2 = r - m;
9
10
11 int L[n1], R[n2];
12
13
14 for (int i = 0; i < n1; i++)
15 L[i] = arr[l + i];
16 for (int j = 0; j < n2; j++)
17 R[j] = arr[m + 1 + j];
18
19
20 int i = 0;
21
22
23 int j = 0;
24
25
26 int k = l;
27
28 while (i < n1 && j < n2) {
29 if (L[i] <= R[j]) {
30 arr[k] = L[i];
31 i++;
32 }
33 else {
34 arr[k] = R[j];
35 j++;
36 }
37 k++;
38 }
39
40
41 while (i < n1) {
42 arr[k] = L[i];
43 i++;
44 k++;
45 }
46
47
48 while (j < n2) {
49 arr[k] = R[j];
50 j++;
51 k++;
52 }
53}
54
55
56void mergeSort(int arr[],int l,int r){
57 if(l>=r){
58 return;
59 }
60 int m = (l+r-1)/2;
61 mergeSort(arr,l,m);
62 mergeSort(arr,m+1,r);
63 merge(arr,l,m,r);
64}
65
66
67void printArray(int A[], int size)
68{
69 for (int i = 0; i < size; i++)
70 cout << A[i] << " ";
71}
72
73
74int main()
75{
76 int arr[] = { 12, 11, 13, 5, 6, 7 };
77 int arr_size = sizeof(arr) / sizeof(arr[0]);
78
79 cout << "Given array is \n";
80 printArray(arr, arr_size);
81
82 mergeSort(arr, 0, arr_size - 1);
83
84 cout << "\nSorted array is \n";
85 printArray(arr, arr_size);
86 return 0;
87}
1#include<iostream>
2using namespace std;
3void swapping(int &a, int &b) { //swap the content of a and b
4 int temp;
5 temp = a;
6 a = b;
7 b = temp;
8}
9void display(int *array, int size) {
10 for(int i = 0; i<size; i++)
11 cout << array[i] << " ";
12 cout << endl;
13}
14void merge(int *array, int l, int m, int r) {
15 int i, j, k, nl, nr;
16 //size of left and right sub-arrays
17 nl = m-l+1; nr = r-m;
18 int larr[nl], rarr[nr];
19 //fill left and right sub-arrays
20 for(i = 0; i<nl; i++)
21 larr[i] = array[l+i];
22 for(j = 0; j<nr; j++)
23 rarr[j] = array[m+1+j];
24 i = 0; j = 0; k = l;
25 //marge temp arrays to real array
26 while(i < nl && j<nr) {
27 if(larr[i] <= rarr[j]) {
28 array[k] = larr[i];
29 i++;
30 }else{
31 array[k] = rarr[j];
32 j++;
33 }
34 k++;
35 }
36 while(i<nl) { //extra element in left array
37 array[k] = larr[i];
38 i++; k++;
39 }
40 while(j<nr) { //extra element in right array
41 array[k] = rarr[j];
42 j++; k++;
43 }
44}
45void mergeSort(int *array, int l, int r) {
46 int m;
47 if(l < r) {
48 int m = l+(r-l)/2;
49 // Sort first and second arrays
50 mergeSort(array, l, m);
51 mergeSort(array, m+1, r);
52 merge(array, l, m, r);
53 }
54}
55int main() {
56 int n;
57 cout << "Enter the number of elements: ";
58 cin >> n;
59 int arr[n]; //create an array with given number of elements
60 cout << "Enter elements:" << endl;
61 for(int i = 0; i<n; i++) {
62 cin >> arr[i];
63 }
64 cout << "Array before Sorting: ";
65 display(arr, n);
66 mergeSort(arr, 0, n-1); //(n-1) for last index
67 cout << "Array after Sorting: ";
68 display(arr, n);
69}