|
| 1 | +#include <iostream> |
| 2 | + |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +// A function to merge the two half into a sorted data. |
| 6 | +void Merge(int *a, int low, int high, int mid) |
| 7 | +{ |
| 8 | + // We have low to mid and mid+1 to high already sorted. |
| 9 | + int i, j, k, temp[high-low+1]; |
| 10 | + i = low; |
| 11 | + k = 0; |
| 12 | + j = mid + 1; |
| 13 | + |
| 14 | + // Merge the two parts into temp[]. |
| 15 | + while (i <= mid && j <= high) |
| 16 | + { |
| 17 | + if (a[i] < a[j]) |
| 18 | + { |
| 19 | + temp[k] = a[i]; |
| 20 | + k++; |
| 21 | + i++; |
| 22 | + } |
| 23 | + else |
| 24 | + { |
| 25 | + temp[k] = a[j]; |
| 26 | + k++; |
| 27 | + j++; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + // Insert all the remaining values from i to mid into temp[]. |
| 32 | + while (i <= mid) |
| 33 | + { |
| 34 | + temp[k] = a[i]; |
| 35 | + k++; |
| 36 | + i++; |
| 37 | + } |
| 38 | + |
| 39 | + // Insert all the remaining values from j to high into temp[]. |
| 40 | + while (j <= high) |
| 41 | + { |
| 42 | + temp[k] = a[j]; |
| 43 | + k++; |
| 44 | + j++; |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | + // Assign sorted data stored in temp[] to a[]. |
| 49 | + for (i = low; i <= high; i++) |
| 50 | + { |
| 51 | + a[i] = temp[i-low]; |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// A function to split array into two parts. |
| 56 | +void MergeSort(int *a, int low, int high) |
| 57 | +{ |
| 58 | + int mid; |
| 59 | + if (low < high) |
| 60 | + { |
| 61 | + mid=(low+high)/2; |
| 62 | + // Split the data into two half. |
| 63 | + MergeSort(a, low, mid); |
| 64 | + MergeSort(a, mid+1, high); |
| 65 | + |
| 66 | + // Merge them to get sorted output. |
| 67 | + Merge(a, low, high, mid); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +int main() |
| 72 | +{ |
| 73 | + int n, i; |
| 74 | + cout<<"\nEnter the number of data element to be sorted: "; |
| 75 | + cin>>n; |
| 76 | + |
| 77 | + int arr[n]; |
| 78 | + for(i = 0; i < n; i++) |
| 79 | + { |
| 80 | + cout<<"Enter element "<<i+1<<": "; |
| 81 | + cin>>arr[i]; |
| 82 | + } |
| 83 | + |
| 84 | + MergeSort(arr, 0, n-1); |
| 85 | + |
| 86 | + // Printing the sorted data. |
| 87 | + cout<<"\nSorted Data "; |
| 88 | + for (i = 0; i < n; i++) |
| 89 | + cout<<"->"<<arr[i]; |
| 90 | + |
| 91 | + return 0; |
| 92 | +} |
0 commit comments