Concept

How are qsort(), lfind(), and bsearch() used in C examples?

ComputerScienceOne / Examples

"We illustrate the usage of these functions in Code Samples 25.2 and 25.3.\n\nCode Sample 25.2: C Search Examples\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include <search.h>\n\n#include \"student.h\"\n\nint main(int argc, char **argv) {\n\nint n = 0;\n\nStudent *roster = loadStudents(\"student.data\", &n);\n\nint i;\n\nsize_t numElems = n;\n\nprintf(\"Roster:\n\n\");\n\nprintStudents(roster, n);\n\n/* Searching */\n\nStudent *castro = NULL;\n\nStudent *castroKey = NULL;\n\nStudent *sandberg = NULL;\n\nchar *str = NULL;\n\ncastro = linearSearchStudentByNuid(roster, 10, 131313);\n\nstr = studentToString(castro);\n\nprintf(\"castro: %s\n\n\", str);\n\nfree(str);\n\n//create a key that will match according to the NUID\n\nint nuid = 23232323;\n\nStudent * key = createEmptyStudent();\n\nkey->nuid = nuid;\n\n//use lfind to find the first such instance:\n\n//sandberg =\n\nsandberg = lfind(key, roster, &numElems, sizeof(Student), studentIdCmp);\n\nstr = studentToString(sandberg);\n\nprintf(\"sandberg: %s\n\n\", str);\n\nfree(str);\n\n//create a key with only the necessary fields\n\ncastroKey = createStudent(\"Starlin\", \"Castro\", 0, 0.0);\n\n//sort according to a comparator function\n\nqsort(roster, n, sizeof(Student), studentLastNameCmp);\n\ncastro = bsearch(castroKey, roster, n, sizeof(Student), studentLastNameCmp);\n\nstr = studentToString(castro);\n\nprintf(\"castro (via binary search): %s\n\n\", str);\n\nfree(str);\n\n//create a key with only the necessary fields\n\ncastroKey = createStudent(NULL, NULL, 131313, 0.0);\n\n//sort according to a comparator function\n\nqsort(roster, n, sizeof(Student), studentIdCmp);\n\ncastro = bsearch(castroKey, roster, n, sizeof(Student), studentIdCmp);\n\nstr = studentToString(castro);\n\nprintf(\"castro (via binary search): %s\n\n\", str);\n\nfree(str);\n\nreturn 0;\n\n}\n\nCode Sample 25.3: C Sort Examples\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include \"student.h\"\n\nint main(int argc, char **argv) {\n\nint n = 0;\n\nStudent *roster = loadStudents(\"student.data\", &n);\n\nint i;\n\nsize_t numElems = n;\n\nprintf(\"Roster:\n\n\");\n\nprintStudents(roster, n);\n\nprintf(\"\n\nSorted by last name/first name:\n\n\");\n\nqsort(roster, numElems, sizeof(Student), studentLastNameCmp);\n\nprintStudents(roster, n);\n\nprintf(\"\n\nSorted by ID:\n\n\");\n\nqsort(roster, numElems, sizeof(Student), studentIdCmp);\n\nprintStudents(roster, n);\n\nprintf(\"\n\nSorted by ID, descending:\n\n\");\n\nqsort(roster, numElems, sizeof(Student), studentIdCmpDesc);\n\nprintStudents(roster, n);\n\nprintf(\"\n\nSorted by GPA:\n\n\");\n\nqsort(roster, numElems, sizeof(Student), studentGPACmp);\n\nprintStudents(roster, n);\n\nreturn 0;\n\n}"

Related Ideas

How are qsort(), lfind(), and bsearch() used in C examples? | ComputerScienceOne | Bifalgorithm | Bifalgorithm