Implementation
#include <iostream>
using namespace std;
int temp[10000];
void mergearrays(int arr[], int l, int mid, int h)
{
int i, j, k;
i = l;
j = mid + 1;
k = l;
while (i <= mid && j <= h)
{
if (arr[i] <= arr[j])
{
temp[k] = arr[i];
i++;
}
else
{
temp[k] = arr[j];
j++;
}
k++;
}
while (i <= mid)
{
temp[k] = arr[i];
i++;
k++;
}
while (j <= h)
{
temp[k] = arr[j];
j++;
k++;
}
for (k = l; k <= h; k++)
{
arr[k] = temp[k];
}
}
void mergesort(int arr[], int l, int h)
{
if (l < h)
{
int mid = (l + h) / 2;
mergesort(arr, l, mid);
mergesort(arr, mid + 1, h);
mergearrays(arr, l, mid, h);
}
}
int main()
{
int arr[] = {4, 1, 20, 12, 11, 9, 5};
int N = 7;
mergesort(arr, 0, N - 1);
cout << "Sorted array: ";
for (int i = 0; i < N; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
Output
Sorted array: 1 4 5 9 11 12 20
0 Comments