冒泡排序函数可以对任意类型的数据排序,函数原型为:

void bubble(void *base, size_t num, size_t width, int(*compare)(const void *elem1, const void *elem2));

参数:1、待排序的数组的首地址

      2、数组中待排序元素的个数

      3、各元素占用空间的大小

      4、指向比较函数的指针,用于确定排序的顺序

compare函数的原型:int compare(const void *elem1,const void *elem2)

以下代码写出了×××数组和字符串数组的比较函数。

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
/*整型数组比较函数*/
int cmp_int(const void *p1, const void *p2)
{
	assert(p1);
	assert(p2);
	//由于只要满足(*(int *)p1 > *(int *)p2))>0时才交换,其余情况都不交换
	return (*(int *)p1 > *(int *)p2) ? 1 : -1;
	//if (*(int *)p1 > *(int *)p2)
	//	return 1;
	//else if (*(int *)p1 == *(int *)p2)
	//	return 0;
	//else return -1;
}
/*字符型数组比较函数*/
int cmp_char(const void *p1,const *p2)
{
	assert(p1);
	assert(p2);
	return strcmp((char *)(*(int *)p1), (char *)(*(int *)p2));
}
/*交换函数*/
void swap(void *p1, void *p2, int size)
{
	assert(p1);
	assert(p2);
	int i = 0;
	for (i = 0; i < size; i++)
	{
		char temp = *((char *)p1+i);
		*((char *)p1+i) = *((char *)p2+i);
		*((char *)p2+i) = temp;
	}
}
/*冒泡排序*/
void bubble(void *base, int count, int length, int(*cmp)(const void *,const void *))//利用回调函数实现
{
	assert(base);
	int i = 0;
	int j = 0;
	for (i = 0; i < count-1; i++)
	{
		for (j = 0; j < count - i - 1; j++)
		{
			if (cmp((char*)base + length*j, (char*)base + length*(j + 1))>0)
				swap((char*)base + length*j, (char*)base + length*(j + 1),length);
		}
	}
}

int main()
{
	int arr[] = { 2, 3, 6, 7, 0, 9, 1, 5, 4, 8 };
	char *str[] = { "cdefc", "dcbar", "aefva", "beksf","cbsle", "cdefg"};
	int len = sizeof(arr) / sizeof(arr[0]);
	int size = sizeof(str) / sizeof(str[0]);
	int i ,j;
	bubble(arr, len,sizeof(int *),cmp_int);
	bubble(str, size,sizeof(char *),cmp_char);
	for (i = 0; i < len; i++)
	{
		printf("%d ",arr[i]);
	}
	printf("\n");
	for (j = 0; j < size; j++)
	{
		printf("%s\n", str[j]);
	}
	system("pause");
	return 0;
}

回调函数:

    简而言之,回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用为调用它所指向的函数时,我们就说这是回调函数。我们要编写一个库,它提供了某些排序算法的实现,如冒泡排序、快速排序、shell排序、shake排序等等。