⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 library_8.html

📁 Linux程序员的工作手册
💻 HTML
字号:
<!-- This HTML file has been created by texi2html 1.27     from library.texinfo on 3 March 1994 --><TITLE>The GNU C Library - Searching and Sorting</TITLE><P>Go to the <A HREF="library_7.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_7.html">previous</A>, <A HREF="library_9.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_9.html">next</A> section.<P><H1><A NAME="SEC86" HREF="library_toc.html#SEC86" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC86">Searching and Sorting</A></H1><P>This chapter describes functions for searching and sorting arrays ofarbitrary objects.  You pass the appropriate comparison function to beapplied as an argument, along with the size of the objects in the arrayand the total number of elements.<P><A NAME="IDX380"></A><H2><A NAME="SEC87" HREF="library_toc.html#SEC87" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC87">Defining the Comparison Function</A></H2><P>In order to use the sorted array library functions, you have to describehow to compare the elements of the array.<P>To do this, you supply a comparison function to compare two elements ofthe array.  The library will call this function, passing as argumentspointers to two array elements to be compared.  Your comparison functionshould return a value the way <CODE>strcmp</CODE> (see section <A HREF="library_5.html#SEC62" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_5.html#SEC62">String/Array Comparison</A>) does: negative if the first argument is "less" than thesecond, zero if they are "equal", and positive if the first argumentis "greater".<P>Here is an example of a comparison function which works with an array ofnumbers of type <CODE>double</CODE>:<P><PRE>intcompare_doubles (const double *a, const double *b){  double temp = *a - *b;  if (temp &#62; 0)    return 1;  else if (temp &#60; 0)    return -1;  else    return 0;}</PRE><P>The header file <TT>`stdlib.h'</TT> defines a name for the data type ofcomparison functions.  This is a GNU extension and thus defined only ifyou request the GNU extensions.<A NAME="IDX381"></A><P><PRE>int comparison_fn_t (const void *, const void *);</PRE><P><A NAME="IDX382"></A><A NAME="IDX383"></A><A NAME="IDX384"></A><H2><A NAME="SEC88" HREF="library_toc.html#SEC88" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC88">Array Search Function</A></H2><P>To search a sorted array for an element matching the key, use the<CODE>bsearch</CODE> function.  The prototype for this function is inthe header file <TT>`stdlib.h'</TT>.<A NAME="IDX385"></A><P><A NAME="IDX386"></A><U>Function:</U> void * <B>bsearch</B> <I>(const void *<VAR>key</VAR>, const void *<VAR>array</VAR>, size_t <VAR>count</VAR>, size_t <VAR>size</VAR>, comparison_fn_t <VAR>compare</VAR>)</I><P>The <CODE>bsearch</CODE> function searches the sorted array <VAR>array</VAR> for an objectthat is equivalent to <VAR>key</VAR>.  The array contains <VAR>count</VAR> elements,each of which is of size <VAR>size</VAR>.<P>The <VAR>compare</VAR> function is used to perform the comparison.  Thisfunction is called with two pointer arguments and should return aninteger less than, equal to, or greater than zero corresponding towhether its first argument is considered less than, equal to, or greaterthan its second argument.  The elements of the <VAR>array</VAR> must alreadybe sorted in ascending order according to this comparison function.<P>The return value is a pointer to the matching array element, or a nullpointer if no match is found.  If the array contains more than one elementthat matches, the one that is returned is unspecified.<P>This function derives its name from the fact that it is implementedusing the binary search.<P><A NAME="IDX387"></A><A NAME="IDX388"></A><A NAME="IDX389"></A><H2><A NAME="SEC89" HREF="library_toc.html#SEC89" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC89">Array Sort Function</A></H2><P>To sort an array using an arbitrary comparison function, use the<CODE>qsort</CODE> function.  The prototype for this function is in<TT>`stdlib.h'</TT>.<A NAME="IDX390"></A><P><A NAME="IDX391"></A><U>Function:</U> void <B>qsort</B> <I>(void *<VAR>array</VAR>, size_t <VAR>count</VAR>, size_t <VAR>size</VAR>, comparison_fn_t <VAR>compare</VAR>)</I><P>The <VAR>qsort</VAR> function sorts the array <VAR>array</VAR>.  The array contains<VAR>count</VAR> elements, each of which is of size <VAR>size</VAR>.<P>The <VAR>compare</VAR> function is used to perform the comparison on thearray elements.  This function is called with two pointer arguments andshould return an integer less than, equal to, or greater than zerocorresponding to whether its first argument is considered less than,equal to, or greater than its second argument.<A NAME="IDX392"></A><P><STRONG>Warning:</STRONG> If two objects compare as equal, their order aftersorting is unpredictable.  That is to say, the sorting is not stable.This can make a difference when the comparison considers only part ofthe elements.  Two elements with the same sort key may differ in otherrespects.<P>If you want the effect of a stable sort, you can get this result bywriting the comparison function so that, lacking other reasondistinguish between two elements, it compares them by their addresses.<P>Here is a simple example of sorting an array of doubles in numericalorder, using the comparison function defined above (see section <A HREF="library_8.html#SEC87" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_8.html#SEC87">Defining the Comparison Function</A>):<P><PRE>{  double *array;  int size;  ...  qsort (array, size, sizeof (double), compare_doubles);}</PRE><P>The <CODE>qsort</CODE> function derives its name from the fact that it wasoriginally implemented using the algorithm "quick sort".<P><H2><A NAME="SEC90" HREF="library_toc.html#SEC90" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC90">Searching and Sorting Example</A></H2><P>Here is an example showing the use of <CODE>qsort</CODE> and <CODE>bsearch</CODE>with an array of structures.  The objects in the array are sortedby comparing their <CODE>name</CODE> fields with the <CODE>strcmp</CODE> function.Then, we can look up individual objects based on their names.<P><PRE>#include &#60;stdlib.h&#62;#include &#60;stdio.h&#62;#include &#60;string.h&#62;/* Define an array of critters to sort.  */struct critter{  char *name;  char *species;};struct critter muppets[]={  {"Kermit", "frog"},  {"Piggy", "pig"},  {"Gonzo", "whatever"},  {"Fozzie", "bear"},  {"Sam", "eagle"},  {"Robin", "frog"},  {"Animal", "animal"},  {"Camilla", "chicken"},  {"Sweetums", "monster"},  {"Dr. Strangepork", "pig"},  {"Link Hogthrob", "pig"},  {"Zoot", "human"},  {"Dr. Bunsen Honeydew", "human"},  {"Beaker", "human"},  {"Swedish Chef", "human"}};int count = sizeof (muppets) / sizeof (struct critter);/* This is the comparison function used for sorting and searching.  */int critter_cmp (const struct critter *c1, const struct critter *c2){  return strcmp (c1-&#62;name, c2-&#62;name);}/* Print information about a critter.  */void print_critter (const struct critter *c){  printf ("%s, the %s\n", c-&#62;name, c-&#62;species);}/* Do the lookup into the sorted array.  */void find_critter (char *name){  struct critter target, *result;  target.name = name;  result = bsearch (&#38;target, muppets, count, sizeof (struct critter),		    critter_cmp);  if (result)    print_critter (result);  else    printf ("Couldn't find %s.\n", name);}/* Main program.  */intmain (void){  int i;  for (i = 0; i &#60; count; i++)    print_critter (&#38;muppets[i]);  printf ("\n");  qsort (muppets, count, sizeof (struct critter), critter_cmp);  for (i = 0; i &#60; count; i++)    print_critter (&#38;muppets[i]);  printf ("\n");  find_critter ("Kermit");  find_critter ("Gonzo");  find_critter ("Janice");  return 0;}</PRE><A NAME="IDX393"></A><P>The output from this program looks like:<P><PRE>Animal, the animalBeaker, the humanCamilla, the chickenDr. Bunsen Honeydew, the humanDr. Strangepork, the pigFozzie, the bearGonzo, the whateverKermit, the frogLink Hogthrob, the pigPiggy, the pigRobin, the frogSam, the eagleSwedish Chef, the humanSweetums, the monsterZoot, the humanKermit, the frogGonzo, the whateverCouldn't find Janice.</PRE><P><P>Go to the <A HREF="library_7.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_7.html">previous</A>, <A HREF="library_9.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_9.html">next</A> section.<P>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -