Search code examples
csortingtypesstructurecriteria

C Language One Sorting Function Chose From 2 Criteria


I was wondering how could I use a single sort function that does the sorting choosing from 2 different criteria. I was thinking to implement the sort function(Sort) having a pointer to another function(Criteria) as an argument. That function Criteria provides me either the (let's say) name or the age of a student, using structures. So a single function that returns two types of data. I think it has to be a void. I want to use bubble sort but I have no idea on how to implement the Criteria function since I want it to return either a char or an int value.


Solution

  • Behave like qsort

    qsort solves the problem by taking a pointer to a comparison function that takes two pointers to structures (left and right) and compares the values pointed at:

    compare( left, right ){
      if( left->field < right->field )
         return -1;
      if( left->field > right->field )
         return 1;
      return 0;
    }
    

    The types left and right are passed in as void* but cast to concrete types. Different implementations of compare give different fields.

    variant structure

    The alternative is a union / struct

     struct data {
        enum Types type;
        union {
            double dblVal;
            int    intVal;
            ....;
        } u;
     };
    

    The type signals the type of data in the union, and the members can then be appropriately read.

    This is the approach taken by lua for its type system.