You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

我的快速排序仅对学生分数排序,为何学生ID未随分数同步交换?

解决方案

问题根因

你当前的代码存在两个核心问题:

  • 现有的swap函数仅支持交换两个int类型的值,排序时只交换了mark分数字段,没有同步处理id字段,导致两个字段不匹配
  • quickSort函数调用partition以及递归调用自身时,参数错误写为未定义的student,而非传入的stu数组

修改步骤

1. 重写swap函数,支持交换完整的Student结构体

C语言支持结构体变量直接赋值,无需单独拆分每个字段交换,修改后的swap函数如下:

void swap(Student* a, Student* b)
{
    Student t = *a;
    *a = *b;
    *b = t;
}

2. 修改partition函数中的swap调用逻辑

不再单独传入mark字段的地址,直接传入结构体元素的地址,保证id和mark同步交换:

int partition (Student stu[], int low, int high) 
{
    int pivot = stu[high].mark; 
    int i = (low - 1);

    for (int j = low; j <= high- 1; j++)
    {
        if (stu[j].mark < pivot)  
        {
            i++; 
            swap(&stu[i], &stu[j]);
        }
    }
    swap(&stu[i + 1], &stu[high]);
    return (i + 1);
}

3. 修复quickSort函数的参数错误

把所有错误的student参数替换为传入的stu数组:

void quickSort(Student stu[], int low, int high)
{
    if (low < high)
    {
        int pi = partition(stu, low, high); 
        quickSort(stu, low, pi - 1);
        quickSort(stu, pi + 1, high);
    }
}

修改完成后排序时会交换整个学生结构体,id和mark会同步移动,不会再出现字段不匹配的问题。


内容的提问来源于stack exchange,提问作者tinkertailor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:48:03