Search code examples
cbubble-sort

Bubble sort for multiable columns?


I have the following code which sorts only for one column only, i want to sort by multiable columns like for example fist name and last name. I want to note that i have tried adding another strcmp statment with && but it didn't give the right result. Here is my code:

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--;
}

Solution

  • Say you want to sort on CarMake, then CarModel, it should be sufficient to just replace:

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

    with:

    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))
    

    So, only if the CarMake values are equal, do we compare on CarModel.

    In terms of efficiency, you may want to only compute the result of the compare once:

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