Using Qsort

Using qsort()

Sort an array of strings

Array declaration:

#define RECORD_SIZE 10 
#define MAX_OUTPUT_ITEMS 10
char output[MAX_OUTPUT_ITEMS][RECORD_SIZE];

Sort the array:

qsort(output, MAX_OUTPUT_ITEMS, RECORD_SIZE, stringCompare);

Compare Strings (is invoked by qsort()):

/*  
 ----------------------------------------------------------------------------
 Function    : stringCompare 
 Description : The comparator function for qsort().         
 ----------------------------------------------------------------------------
 */
int stringCompare(const void *a, const void *b) {    
    // strcmp exactly returns what qsort expects
    // > 1: If a > b 
    // < 0: If b > a
    // 0: If a == b
    int result = strcmp((const char *)a, (const char *)b);    
    return result;
}

Sort characters in an array

char buffer[10];
qsort(buffer, sizeof(buffer), 1, (int(*)(const void *, const void *))charcompare);
 
int charcompare(char *a, char *b) {
      return(*a - *b);
}

Excellent tutorial how to use qsort to compare prices (using structs).

How to sort an array of structs based on the price?

struct st_ex structs[] = {{"mp3 player", 299.0f}, {"plasma tv", 2200.0f}, 
                              {"notebook", 1300.0f}, {"smartphone", 499.99f}, 
                              {"dvd player", 150.0f}, {"matches", 0.2f }};

Solution:
http://www.anyexample.com/programming/c/qsort__sorting_array_of_strings__integers_and_structs.xml

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License