Number Of Page View:100,000+/Months
LOGIN |New User


How would you qsort() function to sort an array of structures?
Using qsort() function we sort an array of structure in c/c++ standard.For Using this function we have to include stdlib.h library.
Representation: basic reoresentaion of qsort() function is,

void qsort(void *Base, size noe , size width, int (*compar)(constt void *, constt void *));

Base-> Pointer indicates beginning of array.  
noe-> Number of Elements.
Width-> Size of Element.
Compare-> Does comparison and returns +ve or -ve integer.It is a callback function (pointer to function). 

This Examples uses structs_sort() function.It is use to compare struct_cmp_product_price() and struct_cmp_product() as compar callbacks.struct_array is used to print structure of array.

void structs_sort(void)
    struct st_eq structs[] = {{"Computer",24000.0f}, {"Laptop", 40000.0f}, 
                              {"Inverter", 10000.0f}, {"A.C.", 20000.0f}, 
                              {"Refrigerator", 7000.0f}, {"Mobile", 15000.0f }};
    size structs_len = sizeof(structs) / sizeof(struct st_eq);
    puts("*** Struct sorting (price)...");
    /* original struct array */
    print_struct_array(structs, structs_len);
    /* sort array using qsort functions */
    qsort(structs, structs_len, sizeof(struct st_ex), struct_cmp_product_price);
    /* print sorted struct array */
    print_struct_array(structs, structs_len);
    puts("*** Struct sorting (product)...");
    /* resort using other comparision function */ 
    qsort(structs, structs_len, sizeof(struct st_eq), struct_cmp_product);    
    /* print sorted struct array */
    print_struct_array(structs, structs_len);
/* MAIN program */
int main()
    /* run all example functions */
    return 0;