【C语言】每日一代码:qsort函数模拟实现(结构体排序)

本文展示了如何在C语言中使用冒泡排序算法对包含姓名和年龄的结构体数组进行排序,分别按姓名和年龄进行比较,并提供了一个测试函数和主函数的示例。
摘要由CSDN通过智能技术生成
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

void bubble_sort2(void* base, size_t sz, size_t width, int (*cmp)(const void*p1, const void*p2))
{
	int i = 0;
	//趟
	for (i = 0; i < sz - 1; i++)
	{
		//每一趟冒泡排序的过程
		int j = 0;
		for (j = 0; j < sz - 1 - i; j++)
		{
			if(cmp((char*)base + j * width, (char*)base + (j + 1) * width)>0)
			{
				Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
			}
		}
	}
}

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

int cmp_stu_by_name(const void* p1, const void*p2)
{
	return strcmp(((struct Stu*)p1)->name, ((struct Stu*)p2)->name);
}

int cmp_stu_by_age(const void* p1, const void* p2)
{
	return ((struct Stu*)p1)->age - ((struct Stu*)p2)->age;
}

void test4()
{
	struct Stu arr[] = { {"zhangsan", 18},{"lisi", 35},{"wangwu", 15}};
	int sz = sizeof(arr) / sizeof(arr[0]);
	bubble_sort2(arr, sz, sizeof(arr[0]), cmp_stu_by_age);
	//打印arr数组的内容
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		printf("%s %d\n", arr[i].name, arr[i].age);
	}
}

int main()
{
	test4();
	return 0;
}

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
假设有如下结构: ```c struct student{ char name[20]; int age; float score; }; ``` 可以通过以下代码使用 `qsort` 函数结构数组 `students` 按照分数从高到低进行排序: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> struct student{ char name[20]; int age; float score; }; int cmp(const void *a, const void *b); int main() { struct student students[5] = {{"Tom", 20, 86.5}, {"Jerry", 19, 92.0}, {"Alice", 21, 78.5}, {"Bob", 18, 95.0}, {"Ted", 20, 88.5}}; int i; printf("Before sorting:\n"); for(i = 0; i < 5; i++){ printf("%s, %d, %.1f\n", students[i].name, students[i].age, students[i].score); } qsort(students, 5, sizeof(struct student), cmp); printf("\nAfter sorting:\n"); for(i = 0; i < 5; i++){ printf("%s, %d, %.1f\n", students[i].name, students[i].age, students[i].score); } return 0; } int cmp(const void *a, const void *b) { struct student *s1 = (struct student *)a; struct student *s2 = (struct student *)b; if(s1->score < s2->score){ return 1; } else if(s1->score > s2->score){ return -1; } else{ return 0; } } ``` 其中,`qsort` 函数的参数依次为: - 待排序的数组名 `students` - 数组中元素的个数 `5` - 每个元素的大小 `sizeof(struct student)` - 比较函数 `cmp` `cmp` 函数用于定义两个元素之间的大小关系,返回值为负数表示第一个元素比第二个元素小,返回值为正数表示第一个元素比第二个元素大,返回值为零表示两个元素相等。在本例中,`cmp` 函数按照分数从高到低进行比较。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值