Sunday, 14 December 2014

Pin It

Widgets

Iterative BubbleSort for Array of Structures


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*
* Implemented by Arjun Sunel.
*/

// 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, j;
 int swapped = 1;
 
 for(i = 0; swapped && i < size - 1; i++)
 {
  swapped = 0;
  for(j = 0; j < size - 1 - i; j++)
  {
  if(IsLessThan(array+j, array+j+1, cmpType) > 0)
   {
    Swap(&array[j], &array[j + 1]);
    swapped = 1;
   }
  }
 }
}

// 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: