Qsort 二级排序

#include <cstdio>
#include <cstdlib>


struct Node{
int x;
int y;
}s[10];


int Comp(const void *a, const void *b)
{
    struct Node *c = (Node *)a;
    struct Node *d = (Node *)b;


    if( c->x != d->x) return c->x - d->x;
    else return c->y -d->y;
}


int main()
{
    for(int i =0; i<5; i++)
    {
        scanf("%d %d",&s[i].x,&s[i].y);
    }
    qsort(s, 5, sizeof(s[0]), Comp);
    for(int i =0;i<5;i++)
    {
        printf("%d %d\n", s[i].x, s[i].y);
    }
    return 0;
}
/*
5 3
5 1
4 2
3 4
6 1
*/

### 如何使用 `qsort` 对结构体数组进行排序 在C语言中,`qsort` 是标准库中的一个通用快速排序函数。为了对结构体数组进行排序,需要提供一个比较函数来指定排序规则。以下是详细的实现方式: #### 使用 `qsort` 排序结构体数组的关键点 1. **定义结构体**:首先定义要排序的结构体类型。 2. **编写比较函数**:创建一个用于比较两个结构体成员的函数,并将其作为参数传递给 `qsort`。 3. **调用 `qsort`**:通过传入结构体数组、元素数量、单个元素大小以及比较函数完成排序。 下面是一个完整的示例代码,展示如何使用 `qsort` 对结构体数组按某个字段升序排列[^1]。 ```c #include <stdio.h> #include <stdlib.h> // 定义结构体 typedef struct { int id; char name[50]; } Person; // 比较函数:按照id字段从小到大排序 int compare_by_id(const void* a, const void* b) { const Person* person_a = (const Person*)a; const Person* person_b = (const Person*)b; if (person_a->id < person_b->id) return -1; // 若第一个小于第二个,返回负值 if (person_a->id > person_b->id) return 1; // 若第一个大于第二个,返回正值 return 0; // 否则相等,返回零值 } int main() { // 初始化结构体数组 Person people[] = { {3, "Alice"}, {1, "Bob"}, {2, "Charlie"} }; size_t n = sizeof(people) / sizeof(people[0]); printf("Before sorting:\n"); for (size_t i = 0; i < n; ++i) { printf("ID: %d, Name: %s\n", people[i].id, people[i].name); } // 调用qsort进行排序 qsort(people, n, sizeof(Person), compare_by_id); printf("\nAfter sorting by ID:\n"); for (size_t i = 0; i < n; ++i) { printf("ID: %d, Name: %s\n", people[i].id, people[i].name); } return 0; } ``` 上述程序展示了如何基于 `Person` 结构体的 `id` 字段进行升序排序。注意,在比较函数中,必须将输入的 `void*` 类型转换为目标结构体类型的指针以便访问其成员变量[^2]。 #### 扩展至多级排序 如果希望执行二级或多级排序(例如先按 `id` 升序再按 `name` 的字母顺序),可以在比较函数中加入额外逻辑。例如修改上面的例子如下所示: ```c int compare_by_id_and_name(const void* a, const void* b) { const Person* person_a = (const Person*)a; const Person* person_b = (const Person*)b; if (person_a->id != person_b->id) { return (person_a->id > person_b->id) ? 1 : -1; } else { return strcmp(person_a->name, person_b->name); // 当id相同,按名字字典序排序 } } ``` 随后只需替换掉原来的比较函数即可实现新的排序需求。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值