Implementation
#include <iostream>
using namespace std;
int temp[10000];
void mergearrays(int arr[], int s, int e)
{
int mid = (s + e) / 2;
int i, j;
i = s;
j = mid + 1;
int x = s;
while (i <= mid && j <= e)
{
if (arr[i] < arr[j])
{
temp[x++] = arr[i];
i++;
}
else
{
temp[x++] = arr[j];
j++;
}
}
while (i <= mid)
{
temp[x++] = arr[i];
i++;
}
while (j <= e)
{
temp[x++] = arr[j];
j++;
}
for (int i = s; i <= e; i++)
arr[i] = temp[i];
}
void mergesort(int arr[], int s, int e)
{
int mid = (s + e) / 2;
/// base case
if (s >= e)
return;
/// recursive case
mergesort(arr, s, mid);
mergesort(arr, mid + 1, e);
mergearrays(arr, s, e);
}
// Driver code
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