Regenerated: /usr/bin/perl scripts/gen-FAQ.pl FAQ.in
[glibc.git] / manual / search.texi
blob0bcbc9b4d3b90d1c6d9e4837e6f2f992abeb41c1
1 @node Searching and Sorting, Pattern Matching, Message Translation, Top
2 @c %MENU% General searching and sorting functions
3 @chapter Searching and Sorting
5 This chapter describes functions for searching and sorting arrays of
6 arbitrary objects.  You pass the appropriate comparison function to be
7 applied as an argument, along with the size of the objects in the array
8 and the total number of elements.
10 @menu
11 * Comparison Functions::        Defining how to compare two objects.
12                                  Since the sort and search facilities
13                                  are general, you have to specify the
14                                  ordering.
15 * Array Search Function::       The @code{bsearch} function.
16 * Array Sort Function::         The @code{qsort} function.
17 * Search/Sort Example::         An example program.
18 * Hash Search Function::        The @code{hsearch} function.
19 * Tree Search Function::        The @code{tsearch} function.
20 @end menu
22 @node Comparison Functions
23 @section Defining the Comparison Function
24 @cindex Comparison Function
26 In order to use the sorted array library functions, you have to describe
27 how to compare the elements of the array.
29 To do this, you supply a comparison function to compare two elements of
30 the array.  The library will call this function, passing as arguments
31 pointers to two array elements to be compared.  Your comparison function
32 should return a value the way @code{strcmp} (@pxref{String/Array
33 Comparison}) does: negative if the first argument is ``less'' than the
34 second, zero if they are ``equal'', and positive if the first argument
35 is ``greater''.
37 Here is an example of a comparison function which works with an array of
38 numbers of type @code{double}:
40 @smallexample
41 int
42 compare_doubles (const double *a, const double *b)
44   return (int) (*a - *b);
46 @end smallexample
48 The header file @file{stdlib.h} defines a name for the data type of
49 comparison functions.  This type is a GNU extension.
51 @comment stdlib.h
52 @comment GNU
53 @tindex comparison_fn_t
54 @smallexample
55 int comparison_fn_t (const void *, const void *);
56 @end smallexample
58 @node Array Search Function
59 @section Array Search Function
60 @cindex search function (for arrays)
61 @cindex binary search function (for arrays)
62 @cindex array search function
64 Generally searching for a specific element in an array means that
65 potentially all elements must be checked.  The GNU C library contains
66 functions to perform linear search.  The prototypes for the following
67 two functions can be found in @file{search.h}.
69 @comment search.h
70 @comment SVID
71 @deftypefun {void *} lfind (const void *@var{key}, void *@var{base}, size_t *@var{nmemb}, size_t @var{size}, comparison_fn_t @var{compar})
72 The @code{lfind} function searches in the array with @code{*@var{nmemb}}
73 elements of @var{size} bytes pointed to by @var{base} for an element
74 which matches the one pointed to by @var{key}.  The function pointed to
75 by @var{compar} is used decide whether two elements match.
77 The return value is a pointer to the matching element in the array
78 starting at @var{base} if it is found.  If no matching element is
79 available @code{NULL} is returned.
81 The mean runtime of this function is @code{*@var{nmemb}}/2.  This
82 function should only be used elements often get added to or deleted from
83 the array in which case it might not be useful to sort the array before
84 searching.
85 @end deftypefun
87 @comment search.h
88 @comment SVID
89 @deftypefun {void *} lsearch (const void *@var{key}, void *@var{base}, size_t *@var{nmemb}, size_t @var{size}, comparison_fn_t @var{compar})
90 The @code{lsearch} function is similar to the @code{lfind} function.  It
91 searches the given array for an element and returns it if found.  The
92 difference is that if no matching element is found the @code{lsearch}
93 function adds the object pointed to by @var{key} (with a size of
94 @var{size} bytes) at the end of the array and it increments the value of
95 @code{*@var{nmemb}} to reflect this addition.
97 This means for the caller that if it is not sure that the array contains
98 the element one is searching for the memory allocated for the array
99 starting at @var{base} must have room for at least @var{size} more
100 bytes.  If one is sure the element is in the array it is better to use
101 @code{lfind} so having more room in the array is always necessary when
102 calling @code{lsearch}.
103 @end deftypefun
105 To search a sorted array for an element matching the key, use the
106 @code{bsearch} function.  The prototype for this function is in
107 the header file @file{stdlib.h}.
108 @pindex stdlib.h
110 @comment stdlib.h
111 @comment ISO
112 @deftypefun {void *} bsearch (const void *@var{key}, const void *@var{array}, size_t @var{count}, size_t @var{size}, comparison_fn_t @var{compare})
113 The @code{bsearch} function searches the sorted array @var{array} for an object
114 that is equivalent to @var{key}.  The array contains @var{count} elements,
115 each of which is of size @var{size} bytes.
117 The @var{compare} function is used to perform the comparison.  This
118 function is called with two pointer arguments and should return an
119 integer less than, equal to, or greater than zero corresponding to
120 whether its first argument is considered less than, equal to, or greater
121 than its second argument.  The elements of the @var{array} must already
122 be sorted in ascending order according to this comparison function.
124 The return value is a pointer to the matching array element, or a null
125 pointer if no match is found.  If the array contains more than one element
126 that matches, the one that is returned is unspecified.
128 This function derives its name from the fact that it is implemented
129 using the binary search algorithm.
130 @end deftypefun
132 @node Array Sort Function
133 @section Array Sort Function
134 @cindex sort function (for arrays)
135 @cindex quick sort function (for arrays)
136 @cindex array sort function
138 To sort an array using an arbitrary comparison function, use the
139 @code{qsort} function.  The prototype for this function is in
140 @file{stdlib.h}.
141 @pindex stdlib.h
143 @comment stdlib.h
144 @comment ISO
145 @deftypefun void qsort (void *@var{array}, size_t @var{count}, size_t @var{size}, comparison_fn_t @var{compare})
146 The @var{qsort} function sorts the array @var{array}.  The array contains
147 @var{count} elements, each of which is of size @var{size}.
149 The @var{compare} function is used to perform the comparison on the
150 array elements.  This function is called with two pointer arguments and
151 should return an integer less than, equal to, or greater than zero
152 corresponding to whether its first argument is considered less than,
153 equal to, or greater than its second argument.
155 @cindex stable sorting
156 @strong{Warning:} If two objects compare as equal, their order after
157 sorting is unpredictable.  That is to say, the sorting is not stable.
158 This can make a difference when the comparison considers only part of
159 the elements.  Two elements with the same sort key may differ in other
160 respects.
162 If you want the effect of a stable sort, you can get this result by
163 writing the comparison function so that, lacking other reason
164 distinguish between two elements, it compares them by their addresses.
165 Note that doing this may make the sorting algorithm less efficient, so
166 do it only if necessary.
168 Here is a simple example of sorting an array of doubles in numerical
169 order, using the comparison function defined above (@pxref{Comparison
170 Functions}):
172 @smallexample
174   double *array;
175   int size;
176   @dots{}
177   qsort (array, size, sizeof (double), compare_doubles);
179 @end smallexample
181 The @code{qsort} function derives its name from the fact that it was
182 originally implemented using the ``quick sort'' algorithm.
183 @end deftypefun
185 @node Search/Sort Example
186 @section Searching and Sorting Example
188 Here is an example showing the use of @code{qsort} and @code{bsearch}
189 with an array of structures.  The objects in the array are sorted
190 by comparing their @code{name} fields with the @code{strcmp} function.
191 Then, we can look up individual objects based on their names.
193 @comment This example is dedicated to the memory of Jim Henson.  RIP.
194 @smallexample
195 @include search.c.texi
196 @end smallexample
198 @cindex Kermit the frog
199 The output from this program looks like:
201 @smallexample
202 Kermit, the frog
203 Piggy, the pig
204 Gonzo, the whatever
205 Fozzie, the bear
206 Sam, the eagle
207 Robin, the frog
208 Animal, the animal
209 Camilla, the chicken
210 Sweetums, the monster
211 Dr. Strangepork, the pig
212 Link Hogthrob, the pig
213 Zoot, the human
214 Dr. Bunsen Honeydew, the human
215 Beaker, the human
216 Swedish Chef, the human
218 Animal, the animal
219 Beaker, the human
220 Camilla, the chicken
221 Dr. Bunsen Honeydew, the human
222 Dr. Strangepork, the pig
223 Fozzie, the bear
224 Gonzo, the whatever
225 Kermit, the frog
226 Link Hogthrob, the pig
227 Piggy, the pig
228 Robin, the frog
229 Sam, the eagle
230 Swedish Chef, the human
231 Sweetums, the monster
232 Zoot, the human
234 Kermit, the frog
235 Gonzo, the whatever
236 Couldn't find Janice.
237 @end smallexample
240 @node Hash Search Function
241 @section The @code{hsearch} function.
243 The functions mentioned so far in this chapter are searching in a sorted
244 or unsorted array.  There are other methods to organize information
245 which later should be searched.  The costs of insert, delete and search
246 differ.  One possible implementation is using hashing tables.
248 @comment search.h
249 @comment SVID
250 @deftypefun int hcreate (size_t @var{nel})
251 The @code{hcreate} function creates a hashing table which can contain at
252 least @var{nel} elements.  There is no possibility to grow this table so
253 it is necessary to choose the value for @var{nel} wisely.  The used
254 methods to implement this function might make it necessary to make the
255 number of elements in the hashing table larger than the expected maximal
256 number of elements.  Hashing tables usually work inefficient if they are
257 filled 80% or more.  The constant access time guaranteed by hashing can
258 only be achieved if few collisions exist.  See Knuth's ``The Art of
259 Computer Programming, Part 3: Searching and Sorting'' for more
260 information.
262 The weakest aspect of this function is that there can be at most one
263 hashing table used through the whole program.  The table is allocated
264 in local memory out of control of the programmer.  As an extension the
265 GNU C library provides an additional set of functions with an reentrant
266 interface which provide a similar interface but which allow to keep
267 arbitrary many hashing tables.
269 It is possible to use more than one hashing table in the program run if
270 the former table is first destroyed by a call to @code{hdestroy}.
272 The function returns a non-zero value if successful.  If it return zero
273 something went wrong.  This could either mean there is already a hashing
274 table in use or the program runs out of memory.
275 @end deftypefun
277 @comment search.h
278 @comment SVID
279 @deftypefun void hdestroy (void)
280 The @code{hdestroy} function can be used to free all the resources
281 allocated in a previous call of @code{hcreate}.  After a call to this
282 function it is again possible to call @code{hcreate} and allocate a new
283 table with possibly different size.
285 It is important to remember that the elements contained in the hashing
286 table at the time @code{hdestroy} is called are @emph{not} freed by this
287 function.  It is the responsibility of the program code to free those
288 strings (if necessary at all).  Freeing all the element memory is not
289 possible without extra, separately kept information since there is no
290 function to iterate through all available elements in the hashing table.
291 If it is really necessary to free a table and all elements the
292 programmer has to keep a list of all table elements and before calling
293 @code{hdestroy} s/he has to free all element's data using this list.
294 This is a very unpleasant mechanism and it also shows that this kind of
295 hashing tables is mainly meant for tables which are created once and
296 used until the end of the program run.
297 @end deftypefun
299 Entries of the hashing table and keys for the search are defined using
300 this type:
302 @deftp {Data type} {struct ENTRY}
303 Both elements of this structure are pointers to zero-terminated strings.
304 This is a limiting restriction of the functionality of the
305 @code{hsearch} functions.  They can only be used for data sets which use
306 the NUL character always and solely to terminate the records.  It is not
307 possible to handle general binary data.
309 @table @code
310 @item char *key
311 Pointer to a zero-terminated string of characters describing the key for
312 the search or the element in the hashing table.
313 @item char *data
314 Pointer to a zero-terminated string of characters describing the data.
315 If the functions will be called only for searching an existing entry
316 this element might stay undefined since it is not used.
317 @end table
318 @end deftp
320 @comment search.h
321 @comment SVID
322 @deftypefun {ENTRY *} hsearch (ENTRY @var{item}, ACTION @var{action})
323 To search in a hashing table created using @code{hcreate} the
324 @code{hsearch} function must be used.  This function can perform simple
325 search for an element (if @var{action} has the @code{FIND}) or it can
326 alternatively insert the key element into the hashing table, possibly
327 replacing a previous value (if @var{action} is @code{ENTER}).
329 The key is denoted by a pointer to an object of type @code{ENTRY}.  For
330 locating the corresponding position in the hashing table only the
331 @code{key} element of the structure is used.
333 The return value depends on the @var{action} parameter value.  If it is
334 @code{FIND} the value is a pointer to the matching element in the
335 hashing table or @code{NULL} if no matching element exists.  If
336 @var{action} is @code{ENTER} the return value is only @code{NULL} if the
337 programs runs out of memory while adding the new element to the table.
338 Otherwise the return value is a pointer to the element in the hashing
339 table which contains newly added element based on the data in @var{key}.
340 @end deftypefun
342 As mentioned before the hashing table used by the functions described so
343 far is global and there can be at any time at most one hashing table in
344 the program.  A solution is to use the following functions which are a
345 GNU extension.  All have in common that they operate on a hashing table
346 which is described by the content of an object of the type @code{struct
347 hsearch_data}.  This type should be treated as opaque, none of its
348 members should be changed directly.
350 @comment search.h
351 @comment GNU
352 @deftypefun int hcreate_r (size_t @var{nel}, struct hsearch_data *@var{htab})
353 The @code{hcreate_r} function initializes the object pointed to by
354 @var{htab} to contain a hashing table with at least @var{nel} elements.
355 So this function is equivalent to the @code{hcreate} function except
356 that the initialized data structure is controlled by the user.
358 This allows to have more than once hashing table at one time.  The
359 memory necessary for the @code{struct hsearch_data} object can be
360 allocated dynamically.
362 The return value is non-zero if the operation were successful.  if the
363 return value is zero something went wrong which probably means the
364 programs runs out of memory.
365 @end deftypefun
367 @comment search.h
368 @comment GNU
369 @deftypefun void hdestroy_r (struct hsearch_data *@var{htab})
370 The @code{hdestroy_r} function frees all resources allocated by the
371 @code{hcreate_r} function for this very same object @var{htab}.  As for
372 @code{hdestroy} it is the programs responsibility to free the strings
373 for the elements of the table.
374 @end deftypefun
376 @comment search.h
377 @comment GNU
378 @deftypefun int hsearch_r (ENTRY @var{item}, ACTION @var{action}, ENTRY **@var{retval}, struct hsearch_data *@var{htab})
379 The @code{hsearch_r} function is equivalent to @code{hsearch}.  The
380 meaning of the first two arguments is identical.  But instead of
381 operating on a single global hashing table the function works on the
382 table described by the object pointed to by @var{htab} (which is
383 initialized by a call to @code{hcreate_r}).
385 Another difference to @code{hcreate} is that the pointer to the found
386 entry in the table is not the return value of the functions.  It is
387 returned by storing it in a pointer variables pointed to by the
388 @var{retval} parameter.  The return value of the function is an integer
389 value indicating success if it is non-zero and failure if it is zero.
390 In the later case the global variable @var{errno} signals the reason for
391 the failure.
393 @table @code
394 @item ENOMEM
395 The table is filled and @code{hsearch_r} was called with an so far
396 unknown key and @var{action} set to @code{ENTER}.
397 @item ESRCH
398 The @var{action} parameter is @code{FIND} and no corresponding element
399 is found in the table.
400 @end table
401 @end deftypefun
404 @node Tree Search Function
405 @section The @code{tsearch} function.
407 Another common form to organize data for efficient search is to use
408 trees.  The @code{tsearch} function family provides a nice interface to
409 functions to organize possibly large amounts of data by providing a mean
410 access time proportional to the logarithm of the number of elements.
411 The GNU C library implementation even guarantees that this bound is
412 never exceeded even for input data which cause problems for simple
413 binary tree implementations.
415 The functions described in the chapter are all described in the @w{System
416 V} and X/Open specifications and are therefore quite portable.
418 In contrast to the @code{hsearch} functions the @code{tsearch} functions
419 can be used with arbitrary data and not only zero-terminated strings.
421 The @code{tsearch} functions have the advantage that no function to
422 initialize data structures is necessary.  A simple pointer of type
423 @code{void *} initialized to @code{NULL} is a valid tree and can be
424 extended or searched.
426 @comment search.h
427 @comment SVID
428 @deftypefun {void *} tsearch (const void *@var{key}, void **@var{rootp}, comparison_fn_t @var{compar})
429 The @code{tsearch} function searches in the tree pointed to by
430 @code{*@var{rootp}} for an element matching @var{key}.  The function
431 pointed to by @var{compar} is used to determine whether two elements
432 match.  @xref{Comparison Functions}, for a specification of the functions
433 which can be used for the @var{compar} parameter.
435 If the tree does not contain a matching entry the @var{key} value will
436 be added to the tree.  @code{tsearch} does not make a copy of the object
437 pointed to by @var{key} (how could it since the size is unknown).
438 Instead it adds a reference to this object which means the object must
439 be available as long as the tree data structure is used.
441 The tree is represented by a pointer to a pointer since it is sometimes
442 necessary to change the root node of the tree.  So it must not be
443 assumed that the variable pointed to by @var{rootp} has the same value
444 after the call.  This also shows that it is not safe to call the
445 @code{tsearch} function more than once at the same time using the same
446 tree.  It is no problem to run it more than once at a time on different
447 trees.
449 The return value is a pointer to the matching element in the tree.  If a
450 new element was created the pointer points to the new data (which is in
451 fact @var{key}).  If an entry had to be created and the program ran out
452 of space @code{NULL} is returned.
453 @end deftypefun
455 @comment search.h
456 @comment SVID
457 @deftypefun {void *} tfind (const void *@var{key}, void *const *@var{rootp}, comparison_fn_t @var{compar})
458 The @code{tfind} function is similar to the @code{tsearch} function.  It
459 locates an element matching the one pointed to by @var{key} and returns
460 a pointer to this element.  But if no matching element is available no
461 new element is entered (note that the @var{rootp} parameter points to a
462 constant pointer).  Instead the function returns @code{NULL}.
463 @end deftypefun
465 Another advantage of the @code{tsearch} function in contrast to the
466 @code{hsearch} functions is that there is an easy way to remove
467 elements.
469 @comment search.h
470 @comment SVID
471 @deftypefun {void *} tdelete (const void *@var{key}, void **@var{rootp}, comparison_fn_t @var{compar})
472 To remove a specific element matching @var{key} from the tree
473 @code{tdelete} can be used.  It locates the matching element using the
474 same method as @code{tfind}.  The corresponding element is then removed
475 and the data if this tree node is returned by the function.  If there is
476 no matching entry in the tree nothing can be deleted and the function
477 returns @code{NULL}.
478 @end deftypefun
480 @comment search.h
481 @comment GNU
482 @deftypefun void tdestroy (void *@var{vroot}, __free_fn_t @var{freefct})
483 If the complete search tree has to be removed one can use
484 @code{tdestroy}.  It frees all resources allocated by the @code{tsearch}
485 function to generate the tree pointed to by @var{vroot}.
487 For the data in each tree node the function @var{freefct} is called.
488 The pointer to the data is passed as the argument to the function.  If
489 no such work is necessary @var{freefct} must point to a function doing
490 nothing.  It is called in any case.
492 This function is a GNU extension and not covered by the @w{System V} or
493 X/Open specifications.
494 @end deftypefun
496 In addition to the function to create and destroy the tree data
497 structure there is another function which allows to apply a function on
498 all elements of the tree.  The function must have this type:
500 @smallexample
501 int __action_fn_t (const void *nodep, VISIT value, int level);
502 @end smallexample
504 The @var{nodep} is the data value of the current node (nce given as the
505 @var{key} argument to @code{tsearch}).  @var{level} is a numeric value
506 which corresponds to the depth of the current node in the tree.  The
507 root node has the depth @math{0} and its children have a depth of
508 @math{1} and so on.  The @code{VISIT} type is an enumeration type.
510 @deftp {Data Type} VISIT
511 The @code{VISIT} value indicates the status of the current node in the
512 tree and how the function is called.  The status of a node is either
513 `leaf' or `internal node'.  For each leaf node the function is called
514 exactly once, for each internal node it is called three times: before
515 the first child is processed, after the first child is processed and
516 after both children are processed.  This makes it possible to handle all
517 three methods of tree traversal (or even a combination of them).
519 @table @code
520 @item preorder
521 The current node is an internal node and the function is called before
522 the first child was processed.
523 @item endorder
524 The current node is an internal node and the function is called after
525 the first child was processed.
526 @item postorder
527 The current node is an internal node and the function is called after
528 the second child was processed.
529 @item leaf
530 The current node is a leaf.
531 @end table
532 @end deftp
534 @comment search.h
535 @comment SVID
536 @deftypefun void twalk (const void *@var{root}, __action_fn_t @var{action})
537 For each node in the tree with a node pointed to by @var{root} the
538 @code{twalk} function calls the function provided by the parameter
539 @var{action}.  For leaf nodes the function is called exactly once with
540 @var{value} set to @code{leaf}.  For internal nodes the function is
541 called three times, setting the @var{value} parameter or @var{action} to
542 the appropriate value.  The @var{level} argument for the @var{action}
543 function is computed while descending the tree with increasing the value
544 by one for the descend to a child, starting with the value @math{0} for
545 the root node.
547 Since the functions used for the @var{action} parameter to @code{twalk}
548 must not modify the tree data it is safe to run @code{twalk} is more
549 than one thread at the same time working on the same tree.  It is also
550 safe to call @code{tfind} in parallel.  Functions which modify the tree
551 must not be used.  Otherwise the behaviour is undefined.
552 @end deftypefun