C++ Program to sort an array using Merge Sort
Program
#include<iostream>
#include<stdlib.h>
#define MAX_SIZE 10
using namespace std;
void sort(int, int);
void merge(int, int, int);
int array[MAX_SIZE];
int main() {
int i, n;
cout << "Enter the number of elements:" << endl;
cin >> n;
cout << "Enter " << n << " elements for Sorting:" << endl;
for (i = 0; i < n; i++)
cin >> array[i];
cout << "Entered data:\t";
for (i = 0; i < n; i++) {
cout << "\t" << array[i];
}
sort(0, n - 1);
cout << endl;
cout << "Sorted Data:\t";
for (i = 0; i < n; i++) {
cout << "\t" << array[i];
}
cout << endl;
return 0;
}
void sort(int low, int high) {
int mid;
if (low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid + 1, high);
merge(low, mid, high);
}
}
void merge(int low, int mid, int high) {
int temp[50];
int i = low, j = mid + 1, k = 0;
while (i <= mid && j <= high) {
if (array[i] < array[j])
temp[k++] = array[i++];
else
temp[k++] = array[j++];
}
while (i <= mid)
temp[k++] = array[i++];
while (j <= high)
temp[k++] = array[j++];
for (i = low, j = 0; i <= high; i++, j++)
array[i] = temp[j];
}
Output
Enter the number of elements:
6
Enter 6 elements for Sorting:
44
87
0
978
-10
14
Entered data: 44 87 0 978 -10 14
Sorted Data: -10 0 14 44 87 978