编写冒泡排序,可以排序整形数组,也可以排序字符串

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

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排序等等。

本文出自 “Scen” 博客,请务必保留此出处http://10741357.blog.51cto.com/10731357/1717798

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值