Thursday, July 22, 2010

qsort: sorting array of strings, integers and structs abstract

qsort: sorting array of strings, integers and structs
abstract
qsort() is standard C function for sorting arrays. It is defined by ISO C standard, and implemented in most C/C++ standard libraries(stdlib.h). This article contains an example of using qsort() for sorting integers, strings and structs.
compatible
# Any ANSI C compiler
# Should work with most C++ compilers

qsort() takes four arguments:

void qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *));

* base — is a pointer to the beginning of data array
* nel — is a number of elements
* width — is a size of each element (in bytes)
* compar — is a callback function (pointer to function), which does comparison and returns positive or negative integer depending on result.

This example contains three separate functions sort_integers_example(), sort_cstrings_example() and sort_structs_example().

* sort_integers_example() uses int_cmp() as compar callback. Additional function print_int_array is used for printing integer array contents.
* sort_cstrings_example() uses cstring_cmp() as compar callback. Additional function print_cstring_array is used for printing string array contents.
* sort_structs_example() uses struct_cmp_by_price() and struct_cmp_by_product() as compar callbacks. Additional function print_struct_array is used for printing array of struct.

參考來源:

"qsort: sorting array of strings, integers and structs abstract  qsort() is standard C function for sorting arrays. It is defined by ISO C standard, and implemented in most C/C++ standard libraries(stdlib.h). This article contains an example of using qsort() for sorting integers, strings and structs."
- qsort: sorting array of strings, integers and structs (在「Google 網頁註解」中檢視)

No comments: