基于冒泡函数的实现qsort()的函数源码


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

struct Stu {
	char name[20];
	int age;
};

//比较函数
int cmp_int(const void* e1, const void* e2) {
	return (*(int*)e1 - *(int*)e2);
}

//比较函数
int cmp_stu_by_age(const void* e1, const void* e2) {
	return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}

void Swap(char* buf1, char* buf2, int width) {
	int i = 0;
	for (i = 0;i < width;i++) {
		char tmp = *buf1;
		*buf1 = *buf2;
		*buf2 = tmp;
		buf1++;
		buf2++;
	}
}

void bubble_sort(void *base, int sz, int width, int(*cmp)(const void *e1, const void *e2)) {
	int i = 0, j = 0;
	int flag = 1;
	int tmp = 0;
	for (i = 0;i < sz - 1;i++) {
		for (j = 0; j < sz - i - 1; j++) {
			if (cmp((char*)base+j*width,(char*)base+(j+1)*width)>0) {
				//交换
				Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
				flag = 0;
			}
			/*if (arr[j] > arr[j + 1]) {
				tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
				flag = 0;
			}*/
		}
		if (flag == 1) {
			break;
		}
	}

}
void text1() {
	int arr[] = { 9,1,2,8,7,6,5,4,0,3 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	int i = 0;
	bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);
	for (i = 0;i < sz;i++) {
		printf("%d ", arr[i]);
	}
}

void text2() {
	struct Stu s1[] = { {"zhangsan",25}, {"lisi",21},{"wangwu",26}};
	int sz = sizeof(s1) / sizeof(s1[0]);
	bubble_sort(s1, sz, sizeof(s1[0]), cmp_stu_by_age);
	int i = 0;
	for (i = 0;i < sz;i++) {
		printf("%s %d ", s1[i].name, s1[i].age);
	}
}

int main() {
	text1();
	printf("\n");
	text2();
	return 0;
}

其中Swap()函数是交换函数,cmp_int()和cmp_stu_by_age()是比较函数,bubble_sort()是函数主体。

text1()是对数组进行冒泡排序

text2()是对结构体的age进行冒泡排序

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值