为什么这种按字母顺序排序的字符串没有';不起作用

本文关键字:字符串 不起作用 排序 顺序 为什么 | 更新日期: 2023-09-27 18:20:35

我一直在做一个程序,它可以用汽车列表做很多事情,检查所有东西,我最不需要做的就是按字符串的字母顺序对这些汽车进行排序

for (int j = 0; j < towns[townNo].townVehicleCount-1; j++) {
    for (int k = 1; k < towns[townNo].townVehicleCount; k++) {
        int identical;
        identical = towns[townNo].Vehicles[j].Brand.CompareTo(towns[townNo].Vehicles[k].Brand);
        if (identical == 1) {
            towns[townNo].Vehicles[towns[townNo].townVehicleCount + 1] = towns[townNo].Vehicles[j];
            towns[townNo].Vehicles[j] = towns[townNo].Vehicles[k];
            towns[townNo].Vehicles[k] = towns[townNo].Vehicles[towns[townNo].townVehicleCount + 1];
        }
        if (identical == -1) {
            towns[townNo].Vehicles[towns[townNo].townVehicleCount + 1] = towns[townNo].Vehicles[k];
            towns[townNo].Vehicles[k] = towns[townNo].Vehicles[j];
            towns[townNo].Vehicles[j] = towns[townNo].Vehicles[towns[townNo].townVehicleCount + 1];
        }
    }
}

为什么这种按字母顺序排序的字符串没有';不起作用

答案非常简单!!

"似乎你总是在元素j和k不同的时候交换它们。删除其中一个if语句,只在元素顺序不正确的时候交换。"

非常感谢@Henrik