[C] 纯文本查看 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int intCmp(void* vp1, void* vp2);
int* initialize(int* arr, int n);
void assign(void*, void*, int);
void merge(void* arr, int p, int q, int r, int elemSize, int (*cmpFunc)(void*, void*));
void mergeSort(void* arr, int p, int r, int elemSize, int (*cmpFunc)(void*, void*));
int main()
{
int n;
printf("Please input a number:");
scanf_s("%d", &n);
int* arr = (int*)malloc(n * sizeof(int)); //分配一个数组
clock_t start = clock(); //返回运行时间毫秒
initialize(arr, n);
clock_t end = clock(); //赋值后再次计算运行时间
printf("inintalize %d numbers costs %lfs\n", n, (double)(end - start) / CLOCKS_PER_SEC); //输出列 输出秒
printf("排序前:\n");
for (int i = 0; i < n; i++) //输出数组
{
printf("%-5d ", arr[i]);
(i + 1) % 10 == 0 ? printf("\n") : printf(""); //输出10位换行
}
start = clock(); //毫秒
mergeSort(arr, 0, n - 1, sizeof(int), intCmp); //数组,0,列,4,,0
end = clock();
printf("\ninsertionSort %d numbers costs %lfs\n", n, (double)(end - start) / CLOCKS_PER_SEC);
printf("排序后:\n");
for (int i = 0; i < n; i++)
{
printf("%-5d ", arr[i]);
(i + 1) % 10 == 0 ? printf("\n") : printf("");
}
free(arr);
return 0;
}
int* initialize(int* arr, int n)
{
for (int i = 0; i < n; i++)
{
arr[i] = rand() % n; //对数组进行赋值
}
return arr;
}
int intCmp(void* vp1, void* vp2) //返回 vp1 - vp2的值
{
return (*(int*)vp1) - (*(int*)vp2);
}
void assign(void* des, void* src, int elemSize)
{
for (int i = 0; i < elemSize; i++)
{
*((char*)des + i) = *((char*)src + i);
}
}
void merge(void* arr, int p, int q, int r, int elemSize, int (*cmpFunc)(void*, void*))
{
int i = p;
int j = q + 1;
int k = 0;
char* temp = (char*)malloc((r - p + 1) * elemSize);
while (i <= q && j <= r) {
if (cmpFunc((char*)arr + i * elemSize, (char*)arr + j * elemSize) < 0) {
assign((char*)temp + k * elemSize, (char*)arr + i * elemSize, elemSize);
i++;
}
else
{
assign((char*)temp + k * elemSize, (char*)arr + j * elemSize, elemSize);
j++;
}
k++;
}
if (i <= q) {
assign((char*)temp + k * elemSize, (char*)arr + i * elemSize, (q - i + 1) * elemSize);
}
if (j <= r) {
assign((char*)temp + k * elemSize, (char*)arr + i * elemSize, (r - j + 1) * elemSize);
}
assign(arr, temp, (r - p + 1) * elemSize);
free(temp);
}
void mergeSort(void* arr, int p, int r, int elemSize, int (*cmpFunc)(void*, void*))
{
int q = 0;
if (p < r) {
q = (r + p) / 2; //二分
mergeSort(arr, p, q, elemSize, cmpFunc); //栈操作,后两位无意义
//mergeSort(arr, q + 1, r, elemSize, cmpFunc); //?
merge(arr, p, q, r, elemSize, cmpFunc);
}
}