Monday, 15 December 2014

Pin It

Widgets

Recursive BubbleSort for Array of Structures


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// enumeration denoting sort type
enum CompareDataType
{
    cmpStringType = 1,
    cmpIntType = 2
};

// Employee structure
struct Employee
{
    char *name;
    int age;
};

// Method to swap two structures by reference.
void Swap(struct Employee *first, struct Employee *second)
{
    struct Employee temp = *first;
    *first = *second;
    *second = temp;
}


int IsLessThan(struct Employee *first, struct Employee* second, enum CompareDataType cmpType)
{
    int res = 0;
    switch (cmpType)
    {
        case cmpStringType:
            res = strcmp(first->name, second->name);
            break;
            
        case cmpIntType:
            res = first->age < second->age ? -1 : (second->age < first->age);
            break;
            
        default:
            fprintf(stderr, "Invalid sort comparison type\n");
            exit(EXIT_FAILURE);
    }
    return res;
}

// Bubble Sort Method
void BubbleSort(struct Employee array[], int size, enum CompareDataType cmpType)
{
    int i, swapped = 0;
    
    if(size <= 1)
        return;
    
    for(i = 0; i < size - 1; i++)
    {
        if (IsLessThan(array+i, array+i+1, cmpType) > 0)
        {
            Swap(&array[i], &array[i + 1]);
            swapped = 1;
        }
    }
    
    if (swapped)
        BubbleSort(array, size-1, cmpType);
}

// Entry point of the program
int main()
{
    struct Employee array[] = {{"John", 45}, {"Mary", 23}, {"Celina", 79}, {"Mike", 41}};
    int arraySize = 4;
    int index;
    
    printf("Before Sorting : \n");
    for(index = 0; index < arraySize; index++)
    {
        printf("(%s, %d) ", array[index].name, array[index].age);
    }
    
    printf("\n");
    
    BubbleSort(array, arraySize, cmpStringType);
    printf("After Sorting by name : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");
    
    BubbleSort(array, arraySize, cmpIntType);
    printf("After Sorting by age : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");       
    return 0;
}

No comments: