Sunday, 14 December 2014

Pin It

Widgets

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

// Insertion Sort Method
void InsertionSort(struct Employee array[], int size, enum CompareDataType cmpType)
{
 int i, j;
 struct Employee curElement;
 
 for(i = 1; i < size; i++)
 {
     curElement = array[i];
  j = i - 1;
  while(j >=0 && (IsLessThan(array+j, &curElement, cmpType) > 0))
  {
   Swap(&array[j+1], &array[j]);
   j--;
  }
  
  array[j+1] = curElement;
 }
}

// 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");
    
    InsertionSort(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");
    
    InsertionSort(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: