通用归并排序
再来写写通用归并排序。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void merge(void* arr, int(*cmp)(void*, void*), int left, int mid, int right, int size)
{
char* tmpArr = (char*)malloc((right - left + 1) * size);
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right)
{
if (cmp((char*)arr + i * size, (char*)arr + j * size) <= 0)
{
memcpy(tmpArr + k * size, (char*)arr + i * size, size);
k++;i++;
}
else
{
memcpy(tmpArr + k * size, (char*)arr + j * size, size);
k++;j++;
}
}
while (i <= mid)
{
memcpy(tmpArr + k * size, (char*)arr + i * size, size);
k++;i++;
}
while (j <= right)
{
memcpy(tmpArr + k * size, (char*)arr + j * size, size);
k++;j++;
}
for (i = 0; i < k; ++i)
{
memcpy((char*)arr + (i + left) * size, tmpArr + i * size, size);
}
}
static void mergesort(void* arr, int(*cmp)(void*, void*), int left, int right, int size)
{
if (left >= right)return;
int mid = (left + right) / 2;
mergesort(arr, cmp, left, mid, size);
mergesort(arr, cmp, mid + 1, right, size);
merge(arr, cmp, left, mid, right, size);
}
void msort(void* arr, int n, int(*cmp)(void*, void*), int size)
{
mergesort(arr, cmp, 0, n - 1, size);
}