多列的冒泡排序?

时间:2013-09-29 19:55:06

标签: c bubble-sort

我有以下代码只对一列进行排序,我想按多个列排序,例如拳头名和姓。我想要注意到我已经尝试添加另一个strcmp语句&&但它没有给出正确的结果。 这是我的代码:

struct Car tempCar;
 tempCar.CarMake  = (char*)malloc( 200 *sizeof(char));
 tempCar.CarMakeYear  = (char*)malloc( 200 *sizeof(char));
 tempCar.CarModel  = (char*)malloc( 200 *sizeof(char));
 tempCar.Occurances = 0;  

int g, didSwap = 1, limit = newCarsCounter - 1; 

//Sort by make
while (didSwap) {
    didSwap = 0;
    for (g = 0; g < newCarsCounter; g++) {
        if ((strcmp (newCars[g].CarMake, newCars[g+1].CarMake) > 0))
        {
            tempCar.CarMake = newCars[g].CarMake;
            tempCar.CarModel = newCars[g].CarModel;
            tempCar.CarMakeYear = newCars[g].CarMakeYear;
            tempCar.Occurances = newCars[g].Occurances;

            newCars[g].CarMake = newCars[g+1].CarMake;
            newCars[g].CarModel = newCars[g+1].CarModel;
            newCars[g].CarMakeYear = newCars[g+1].CarMakeYear;
            newCars[g].Occurances = newCars[g+1].Occurances;

            newCars[g+1].CarMake = tempCar.CarMake;
            newCars[g+1].CarModel = tempCar.CarModel;
            newCars[g+1].CarMakeYear = tempCar.CarMakeYear;
            newCars[g+1].Occurances = tempCar.Occurances;

            didSwap = 1;
        }
    }
    limit--;
}

2 个答案:

答案 0 :(得分:1)

假设您要对CarMake进行排序,然后CarModel,则只需替换即可:

if ((strcmp (newCars[g].CarMake, newCars[g+1].CarMake) > 0))

使用:

if (strcmp(newCars[g].CarMake, newCars[g+1].CarMake) > 0 ||
    (strcmp(newCars[g].CarMake, newCars[g+1].CarMake) == 0 &&
     strcmp(newCars[g].CarModel, newCars[g+1].CarModel) > 0))

因此,只有当CarMake值相等时,我们才能在CarModel上进行比较。

就效率而言,您可能只希望计算比较结果一次:

int compareVal = strcmp(newCars[g].CarMake, newCars[g+1].CarMake);
if (compareVal > 0 ||
    (compareVal == 0 &&
     strcmp(newCars[g].CarModel, newCars[g+1].CarModel) > 0))

答案 1 :(得分:0)

如果您想按型号排序:

int CompareCar (struct Car *a, struct Car *b) {
    int cmp = strcmp(a->CarMake, b->CarMake);
    if (cmp != 0) {
        return cmp;
    } else { // equal makes, compare by model
        return strcmp(a->CarModel, b->CarModel);
    }
}

可以缩短为:

int ComapreCar (struct Car *a, struct Car *b) {
    return strcmp(a->CarMake, b->CarMake) || strcmp(a->CarModel, b->CarModel);
}

然后替换

if ((strcmp (newCars[g].CarMake, newCars[g+1].CarMake) > 0))

if (CompareCar(&(newCars[g]), &(newCars[g+1]) > 0)