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

如何在C语言中根据一个数组对另外两个关联数组排序

同步排序三个关联数组的解决方案

方法一:修改现有冒泡排序代码,同步交换对应元素

你当前的冒泡排序只处理了remain数组,要同步调整model和price,只需在交换remain元素的代码块里,同时交换另外两个数组的对应位置元素即可。

修改后的descendingOrder函数如下:

// 传入三个数组和长度,避免依赖全局变量
void descendingOrder(char *model[], int price[], int remain[], int size) {
    int i, j;
    int tempPrice;
    char *tempModel;
    int tempRemain;
    
    for (i = 0; i < size; ++i) {
        for (j = i + 1; j < size; ++j) {
            if (remain[i] < remain[j]) {
                // 交换remain数组元素
                tempRemain = remain[i];
                remain[i] = remain[j];
                remain[j] = tempRemain;
                
                // 同步交换price数组对应元素
                tempPrice = price[i];
                price[i] = price[j];
                price[j] = tempPrice;
                
                // 同步交换model数组对应指针
                tempModel = model[i];
                model[i] = model[j];
                model[j] = tempModel;
            }
        }
    }
}

调用时直接传三个数组和长度10:

descendingOrder(model, price, remain, 10);

方法二:用结构体整合关联数据(更推荐)

把汽车的型号、价格、库存三个关联字段放到一个结构体里,排序时直接对结构体数组操作,逻辑更清晰,也不会出现数组错位的问题。

示例代码:

#include <stdio.h>

// 定义汽车结构体,整合所有关联数据
typedef struct {
    char model[20];
    int price;
    int remain;
} Car;

void sortCarsDescending(Car cars[], int size) {
    int i, j;
    Car temp;
    
    for (i = 0; i < size; ++i) {
        for (j = i + 1; j < size; ++j) {
            if (cars[i].remain < cars[j].remain) {
                // 交换整个结构体,所有关联数据同步调整
                temp = cars[i];
                cars[i] = cars[j];
                cars[j] = temp;
            }
        }
    }
}

int main() {
    // 初始化结构体数组
    Car cars[] = {
        {"Honda ", 750000, 3},
        {"Audi  ", 650000, 4},
        {"Ferrari", 950000, 5},
        {"Nissan", 300000, 3},
        {"Toyota", 900000, 3},
        {"Bugatti", 190000, 7},
        {"Tesla ", 400000, 8},
        {"Jensen", 750000, 2},
        {"Porsche", 300000, 1},
        {"Suzuki", 800000, 2}
    };
    int size = sizeof(cars) / sizeof(cars[0]);
    
    // 执行排序
    sortCarsDescending(cars, size);
    
    // 验证排序结果
    for (int i = 0; i < size; ++i) {
        printf("型号:%s,价格:%d,库存:%d\n", cars[i].model, cars[i].price, cars[i].remain);
    }
    
    return 0;
}

这种方式把关联数据绑定在一起,排序时无需单独处理每个数组,代码可读性和可维护性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:25:22