#include <stdio.h>
#include <stdlib.h>
void merge(int left, int mid, int right, int arr[])
{
int n1 = mid - left + 1;
int n2 = right - mid;
int left_arr[n1];
int right_arr[n2];
for (int i = 0; i < n1; i++)
{
left_arr[i] = arr[left + i];
}
for (int i = 0; i < n2; i++)
{
right_arr[i] = arr[mid + 1 + i];
}
int idx=left, p =0, q = 0;
while (p < n1 && q < n2)
{
if (left_arr[p] <= right_arr[q])
{
arr[idx++] = left_arr[p++];
}
else
{
arr[idx++] = right_arr[q++];
}
}
while (p < n1)
{
arr[idx++] = left_arr[p++];
}
while(q < n2)
{
arr[idx++] = right_arr[q++];
}
}
void merge_sort(int left, int right, int arr[])
{
if (left < right)
{
int mid = (left + right) / 2;
merge_sort(left, mid, arr);
merge_sort(mid + 1, right, arr);
merge(left, mid, right, arr);
for (int i =0; i <8; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
return;
}
int main(void)
{
int arr[8] = {3, 21, 5, 9, 2, 64, 17, 24};
merge_sort(0, 7, arr);
return 0;
}