|
| 1 | +#include<iostream> |
| 2 | +using namespace std; |
| 3 | +void 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 | +} |
| 9 | +void display(int *array, int size) { |
| 10 | + for(int i = 0; i<size; i++) |
| 11 | + cout << array[i] << " "; |
| 12 | + cout << endl; |
| 13 | +} |
| 14 | +void 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 | + //merge 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 | +} |
| 45 | +void 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 | +} |
| 55 | +int 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 | +} |
0 commit comments