归并排序

#include <stdio.h>
#include <stdlib.h>

typedef int (*CallbackFunc)(void *a, void *b);

int cmpare(void *a, void *b);

void merge_sort(void **arr, int size, CallbackFunc cmp);

void merge_partion_sort(void **back, void **arr, int low, int mid, int high, CallbackFunc cmp);

int main()
{
	int arr[] = {1, 5, 4, 3, 2, 7, 6, 9, 8, 0};
	merge_sort(arr, 10, cmpare);
	
	int i = 0;
	for (i = 0; i < 10; i ++) {
		printf("%d\n", arr[i]);
	}
	
	return 0;
}

int cmpare(void *a, void *b)
{
	return (int)a - (int)b;
}

void merge_sort(void **arr, int size, CallbackFunc cmp)
{
	void **back = NULL;
	
	back = (void **)malloc(sizeof(void *) * size);
	
	merge_partion_sort(back, arr, 0, size>>1, size, cmp);
}

void merge_partion_sort(void **back, void **arr, int low, int mid, int high, CallbackFunc cmp)
{
	int i = low;
	int j = low;
	int k = mid;
	
	if ((low + 1) < mid) {
		int x = low + ((mid - low) >> 1);
		merge_partion_sort(back, arr, low, x, mid, cmp);
	}
	
	if ((mid + 1) < high) {
		int x = mid + ((high - mid) >> 1);
		merge_partion_sort(back, arr, mid, x, high, cmp);
	}
	
	while (j < mid && k < high) {
		if (cmp(arr[j], arr[k]) < 0) {
			back[i] = arr[j];
			j ++;
		} else {
			back[i] = arr[k];
			k ++;
		}
		i ++;
	}
	
	while (j < mid) {
		back[i] = arr[j];
		i ++;
		j ++;
	}
	
	while (k < high) {
		back[i] = arr[k];
		i ++;
		k ++;
	}
	
	for (i = low; i < high; i ++) {
		arr[i] = back[i];
	}
}

你可能感兴趣的:(归并排序)