stdlib: Remove use of mergesort on qsort (BZ 21719)
[glibc.git] / manual / search.texi
bloba550858478f7fc83168db83ebb4f678cac880c47
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 void *a, const void *b)
44   const double *da = (const double *) a;
45   const double *db = (const double *) b;
47   return (*da > *db) - (*da < *db);
49 @end smallexample
51 The header file @file{stdlib.h} defines a name for the data type of
52 comparison functions.  This type is a GNU extension.
54 @comment stdlib.h
55 @comment GNU
56 @tindex comparison_fn_t
57 @smallexample
58 int comparison_fn_t (const void *, const void *);
59 @end smallexample
61 @node Array Search Function
62 @section Array Search Function
63 @cindex search function (for arrays)
64 @cindex binary search function (for arrays)
65 @cindex array search function
67 Generally searching for a specific element in an array means that
68 potentially all elements must be checked.  @Theglibc{} contains
69 functions to perform linear search.  The prototypes for the following
70 two functions can be found in @file{search.h}.
72 @deftypefun {void *} lfind (const void *@var{key}, const void *@var{base}, size_t *@var{nmemb}, size_t @var{size}, comparison_fn_t @var{compar})
73 @standards{SVID, search.h}
74 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
75 The @code{lfind} function searches in the array with @code{*@var{nmemb}}
76 elements of @var{size} bytes pointed to by @var{base} for an element
77 which matches the one pointed to by @var{key}.  The function pointed to
78 by @var{compar} is used to decide whether two elements match.
80 The return value is a pointer to the matching element in the array
81 starting at @var{base} if it is found.  If no matching element is
82 available @code{NULL} is returned.
84 The mean runtime of this function is @code{*@var{nmemb}}/2.  This
85 function should only be used if elements often get added to or deleted from
86 the array in which case it might not be useful to sort the array before
87 searching.
88 @end deftypefun
90 @deftypefun {void *} lsearch (const void *@var{key}, void *@var{base}, size_t *@var{nmemb}, size_t @var{size}, comparison_fn_t @var{compar})
91 @standards{SVID, search.h}
92 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
93 @c A signal handler that interrupted an insertion and performed an
94 @c insertion itself would leave the array in a corrupt state (e.g. one
95 @c new element initialized twice, with parts of both initializations
96 @c prevailing, and another uninitialized element), but this is just a
97 @c special case of races on user-controlled objects, that have to be
98 @c avoided by users.
100 @c In case of cancellation, we know the array won't be left in a corrupt
101 @c state; the new element is initialized before the element count is
102 @c incremented, and the compiler can't reorder these operations because
103 @c it can't know that they don't alias.  So, we'll either cancel after
104 @c the increment and the initialization are both complete, or the
105 @c increment won't have taken place, and so how far the initialization
106 @c got doesn't matter.
107 The @code{lsearch} function is similar to the @code{lfind} function.  It
108 searches the given array for an element and returns it if found.  The
109 difference is that if no matching element is found the @code{lsearch}
110 function adds the object pointed to by @var{key} (with a size of
111 @var{size} bytes) at the end of the array and it increments the value of
112 @code{*@var{nmemb}} to reflect this addition.
114 This means for the caller that if it is not sure that the array contains
115 the element one is searching for the memory allocated for the array
116 starting at @var{base} must have room for at least @var{size} more
117 bytes.  If one is sure the element is in the array it is better to use
118 @code{lfind} so having more room in the array is always necessary when
119 calling @code{lsearch}.
120 @end deftypefun
122 To search a sorted array for an element matching the key, use the
123 @code{bsearch} function.  The prototype for this function is in
124 the header file @file{stdlib.h}.
125 @pindex stdlib.h
127 @deftypefun {void *} bsearch (const void *@var{key}, const void *@var{array}, size_t @var{count}, size_t @var{size}, comparison_fn_t @var{compare})
128 @standards{ISO, stdlib.h}
129 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
130 The @code{bsearch} function searches the sorted array @var{array} for an object
131 that is equivalent to @var{key}.  The array contains @var{count} elements,
132 each of which is of size @var{size} bytes.
134 The @var{compare} function is used to perform the comparison.  This
135 function is called with two pointer arguments and should return an
136 integer less than, equal to, or greater than zero corresponding to
137 whether its first argument is considered less than, equal to, or greater
138 than its second argument.  The elements of the @var{array} must already
139 be sorted in ascending order according to this comparison function.
141 The return value is a pointer to the matching array element, or a null
142 pointer if no match is found.  If the array contains more than one element
143 that matches, the one that is returned is unspecified.
145 This function derives its name from the fact that it is implemented
146 using the binary search algorithm.
147 @end deftypefun
149 @node Array Sort Function
150 @section Array Sort Function
151 @cindex sort function (for arrays)
152 @cindex quick sort function (for arrays)
153 @cindex array sort function
155 To sort an array using an arbitrary comparison function, use the
156 @code{qsort} function.  The prototype for this function is in
157 @file{stdlib.h}.
158 @pindex stdlib.h
160 @deftypefun void qsort (void *@var{array}, size_t @var{count}, size_t @var{size}, comparison_fn_t @var{compare})
161 @standards{ISO, stdlib.h}
162 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
163 The @code{qsort} function sorts the array @var{array}.  The array
164 contains @var{count} elements, each of which is of size @var{size}.
166 The @var{compare} function is used to perform the comparison on the
167 array elements.  This function is called with two pointer arguments and
168 should return an integer less than, equal to, or greater than zero
169 corresponding to whether its first argument is considered less than,
170 equal to, or greater than its second argument.
172 @cindex stable sorting
173 @strong{Warning:} If two objects compare as equal, their order after
174 sorting is unpredictable.  That is to say, the sorting is not stable.
175 This can make a difference when the comparison considers only part of
176 the elements.  Two elements with the same sort key may differ in other
177 respects.
179 Although the object addresses passed to the comparison function lie
180 within the array, they need not correspond with the original locations
181 of those objects because the sorting algorithm may swap around objects
182 in the array before making some comparisons.  The only way to perform
183 a stable sort with @code{qsort} is to first augment the objects with a
184 monotonic counter of some kind.
186 Here is a simple example of sorting an array of doubles in numerical
187 order, using the comparison function defined above (@pxref{Comparison
188 Functions}):
190 @smallexample
192   double *array;
193   int size;
194   @dots{}
195   qsort (array, size, sizeof (double), compare_doubles);
197 @end smallexample
199 The @code{qsort} function derives its name from the fact that it was
200 originally implemented using the ``quick sort'' algorithm.
202 The implementation of @code{qsort} in this library is an in-place sort
203 and uses a constant extra space (allocated on the stack).
204 @end deftypefun
206 @node Search/Sort Example
207 @section Searching and Sorting Example
209 Here is an example showing the use of @code{qsort} and @code{bsearch}
210 with an array of structures.  The objects in the array are sorted
211 by comparing their @code{name} fields with the @code{strcmp} function.
212 Then, we can look up individual objects based on their names.
214 @comment This example is dedicated to the memory of Jim Henson.  RIP.
215 @smallexample
216 @include search.c.texi
217 @end smallexample
219 @cindex Kermit the frog
220 The output from this program looks like:
222 @smallexample
223 Kermit, the frog
224 Piggy, the pig
225 Gonzo, the whatever
226 Fozzie, the bear
227 Sam, the eagle
228 Robin, the frog
229 Animal, the animal
230 Camilla, the chicken
231 Sweetums, the monster
232 Dr. Strangepork, the pig
233 Link Hogthrob, the pig
234 Zoot, the human
235 Dr. Bunsen Honeydew, the human
236 Beaker, the human
237 Swedish Chef, the human
239 Animal, the animal
240 Beaker, the human
241 Camilla, the chicken
242 Dr. Bunsen Honeydew, the human
243 Dr. Strangepork, the pig
244 Fozzie, the bear
245 Gonzo, the whatever
246 Kermit, the frog
247 Link Hogthrob, the pig
248 Piggy, the pig
249 Robin, the frog
250 Sam, the eagle
251 Swedish Chef, the human
252 Sweetums, the monster
253 Zoot, the human
255 Kermit, the frog
256 Gonzo, the whatever
257 Couldn't find Janice.
258 @end smallexample
261 @node Hash Search Function
262 @section The @code{hsearch} function.
264 The functions mentioned so far in this chapter are for searching in a sorted
265 or unsorted array.  There are other methods to organize information
266 which later should be searched.  The costs of insert, delete and search
267 differ.  One possible implementation is using hashing tables.
268 The following functions are declared in the header file @file{search.h}.
270 @deftypefun int hcreate (size_t @var{nel})
271 @standards{SVID, search.h}
272 @safety{@prelim{}@mtunsafe{@mtasurace{:hsearch}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
273 @c hcreate @mtasurace:hsearch @ascuheap @acucorrupt @acsmem
274 @c  hcreate_r dup @mtsrace:htab @ascuheap @acucorrupt @acsmem
275 The @code{hcreate} function creates a hashing table which can contain at
276 least @var{nel} elements.  There is no possibility to grow this table so
277 it is necessary to choose the value for @var{nel} wisely.  The method
278 used to implement this function might make it necessary to make the
279 number of elements in the hashing table larger than the expected maximal
280 number of elements.  Hashing tables usually work inefficiently if they are
281 filled 80% or more.  The constant access time guaranteed by hashing can
282 only be achieved if few collisions exist.  See Knuth's ``The Art of
283 Computer Programming, Part 3: Searching and Sorting'' for more
284 information.
286 The weakest aspect of this function is that there can be at most one
287 hashing table used through the whole program.  The table is allocated
288 in local memory out of control of the programmer.  As an extension @theglibc{}
289 provides an additional set of functions with a reentrant
290 interface which provides a similar interface but which allows keeping
291 arbitrarily many hashing tables.
293 It is possible to use more than one hashing table in the program run if
294 the former table is first destroyed by a call to @code{hdestroy}.
296 The function returns a non-zero value if successful.  If it returns zero,
297 something went wrong.  This could either mean there is already a hashing
298 table in use or the program ran out of memory.
299 @end deftypefun
301 @deftypefun void hdestroy (void)
302 @standards{SVID, search.h}
303 @safety{@prelim{}@mtunsafe{@mtasurace{:hsearch}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
304 @c hdestroy @mtasurace:hsearch @ascuheap @acucorrupt @acsmem
305 @c  hdestroy_r dup @mtsrace:htab @ascuheap @acucorrupt @acsmem
306 The @code{hdestroy} function can be used to free all the resources
307 allocated in a previous call of @code{hcreate}.  After a call to this
308 function it is again possible to call @code{hcreate} and allocate a new
309 table with possibly different size.
311 It is important to remember that the elements contained in the hashing
312 table at the time @code{hdestroy} is called are @emph{not} freed by this
313 function.  It is the responsibility of the program code to free those
314 strings (if necessary at all).  Freeing all the element memory is not
315 possible without extra, separately kept information since there is no
316 function to iterate through all available elements in the hashing table.
317 If it is really necessary to free a table and all elements the
318 programmer has to keep a list of all table elements and before calling
319 @code{hdestroy} s/he has to free all element's data using this list.
320 This is a very unpleasant mechanism and it also shows that this kind of
321 hashing table is mainly meant for tables which are created once and
322 used until the end of the program run.
323 @end deftypefun
325 Entries of the hashing table and keys for the search are defined using
326 this type:
328 @deftp {Data type} ENTRY
329 @table @code
330 @item char *key
331 Pointer to a zero-terminated string of characters describing the key for
332 the search or the element in the hashing table.
334 This is a limiting restriction of the functionality of the
335 @code{hsearch} functions: They can only be used for data sets which
336 use the NUL character always and solely to terminate keys.  It is not
337 possible to handle general binary data for keys.
339 @item void *data
340 Generic pointer for use by the application.  The hashing table
341 implementation preserves this pointer in entries, but does not use it
342 in any way otherwise.
343 @end table
344 @end deftp
346 @deftp {Data type} {struct entry}
347 The underlying type of @code{ENTRY}.
348 @end deftp
350 @deftypefun {ENTRY *} hsearch (ENTRY @var{item}, ACTION @var{action})
351 @standards{SVID, search.h}
352 @safety{@prelim{}@mtunsafe{@mtasurace{:hsearch}}@asunsafe{}@acunsafe{@acucorrupt{/action==ENTER}}}
353 @c hsearch @mtasurace:hsearch @acucorrupt/action==ENTER
354 @c  hsearch_r dup @mtsrace:htab @acucorrupt/action==ENTER
355 To search in a hashing table created using @code{hcreate} the
356 @code{hsearch} function must be used.  This function can perform a simple
357 search for an element (if @var{action} has the value @code{FIND}) or it can
358 alternatively insert the key element into the hashing table.  Entries
359 are never replaced.
361 The key is denoted by a pointer to an object of type @code{ENTRY}.  For
362 locating the corresponding position in the hashing table only the
363 @code{key} element of the structure is used.
365 If an entry with a matching key is found the @var{action} parameter is
366 irrelevant.  The found entry is returned.  If no matching entry is found
367 and the @var{action} parameter has the value @code{FIND} the function
368 returns a @code{NULL} pointer.  If no entry is found and the
369 @var{action} parameter has the value @code{ENTER} a new entry is added
370 to the hashing table which is initialized with the parameter @var{item}.
371 A pointer to the newly added entry is returned.
372 @end deftypefun
374 As mentioned before, the hashing table used by the functions described so
375 far is global and there can be at any time at most one hashing table in
376 the program.  A solution is to use the following functions which are a
377 GNU extension.  All have in common that they operate on a hashing table
378 which is described by the content of an object of the type @code{struct
379 hsearch_data}.  This type should be treated as opaque, none of its
380 members should be changed directly.
382 @deftypefun int hcreate_r (size_t @var{nel}, struct hsearch_data *@var{htab})
383 @standards{GNU, search.h}
384 @safety{@prelim{}@mtsafe{@mtsrace{:htab}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
385 @c Unlike the lsearch array, the htab is (at least in part) opaque, so
386 @c let's make it absolutely clear that ensuring exclusive access is a
387 @c caller responsibility.
389 @c Cancellation is unlikely to leave the htab in a corrupt state: the
390 @c last field to be initialized is the one that tells whether the entire
391 @c data structure was initialized, and there's a function call (calloc)
392 @c in between that will often ensure all other fields are written before
393 @c the table.  However, should this call be inlined (say with LTO), this
394 @c assumption may not hold.  The calloc call doesn't cross our library
395 @c interface barrier, so let's consider this could happen and mark this
396 @c with @acucorrupt.  It's no safety loss, since we already have
397 @c @ascuheap anyway...
399 @c hcreate_r @mtsrace:htab @ascuheap @acucorrupt @acsmem
400 @c  isprime ok
401 @c  calloc dup @ascuheap @acsmem
402 The @code{hcreate_r} function initializes the object pointed to by
403 @var{htab} to contain a hashing table with at least @var{nel} elements.
404 So this function is equivalent to the @code{hcreate} function except
405 that the initialized data structure is controlled by the user.
407 This allows having more than one hashing table at one time.  The memory
408 necessary for the @code{struct hsearch_data} object can be allocated
409 dynamically.  It must be initialized with zero before calling this
410 function.
412 The return value is non-zero if the operation was successful.  If the
413 return value is zero, something went wrong, which probably means the
414 program ran out of memory.
415 @end deftypefun
417 @deftypefun void hdestroy_r (struct hsearch_data *@var{htab})
418 @standards{GNU, search.h}
419 @safety{@prelim{}@mtsafe{@mtsrace{:htab}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
420 @c The table is released while the table pointer still points to it.
421 @c Async cancellation is thus unsafe, but it already was because we call
422 @c free().  Using the table in a handler while it's being released would
423 @c also be dangerous, but calling free() already makes it unsafe, and
424 @c the requirement on the caller to ensure exclusive access already
425 @c guarantees this doesn't happen, so we don't get @asucorrupt.
427 @c hdestroy_r @mtsrace:htab @ascuheap @acucorrupt @acsmem
428 @c  free dup @ascuheap @acsmem
429 The @code{hdestroy_r} function frees all resources allocated by the
430 @code{hcreate_r} function for this very same object @var{htab}.  As for
431 @code{hdestroy} it is the program's responsibility to free the strings
432 for the elements of the table.
433 @end deftypefun
435 @deftypefun int hsearch_r (ENTRY @var{item}, ACTION @var{action}, ENTRY **@var{retval}, struct hsearch_data *@var{htab})
436 @standards{GNU, search.h}
437 @safety{@prelim{}@mtsafe{@mtsrace{:htab}}@assafe{}@acunsafe{@acucorrupt{/action==ENTER}}}
438 @c Callers have to ensure mutual exclusion; insertion, if cancelled,
439 @c leaves the table in a corrupt state.
441 @c hsearch_r @mtsrace:htab @acucorrupt/action==ENTER
442 @c  strlen dup ok
443 @c  strcmp dup ok
444 The @code{hsearch_r} function is equivalent to @code{hsearch}.  The
445 meaning of the first two arguments is identical.  But instead of
446 operating on a single global hashing table the function works on the
447 table described by the object pointed to by @var{htab} (which is
448 initialized by a call to @code{hcreate_r}).
450 Another difference to @code{hcreate} is that the pointer to the found
451 entry in the table is not the return value of the function.  It is
452 returned by storing it in a pointer variable pointed to by the
453 @var{retval} parameter.  The return value of the function is an integer
454 value indicating success if it is non-zero and failure if it is zero.
455 In the latter case the global variable @code{errno} signals the reason for
456 the failure.
458 @table @code
459 @item ENOMEM
460 The table is filled and @code{hsearch_r} was called with a so far
461 unknown key and @var{action} set to @code{ENTER}.
462 @item ESRCH
463 The @var{action} parameter is @code{FIND} and no corresponding element
464 is found in the table.
465 @end table
466 @end deftypefun
469 @node Tree Search Function
470 @section The @code{tsearch} function.
472 Another common form to organize data for efficient search is to use
473 trees.  The @code{tsearch} function family provides a nice interface to
474 functions to organize possibly large amounts of data by providing a mean
475 access time proportional to the logarithm of the number of elements.
476 @Theglibc{} implementation even guarantees that this bound is
477 never exceeded even for input data which cause problems for simple
478 binary tree implementations.
480 The functions described in the chapter are all described in the @w{System
481 V} and X/Open specifications and are therefore quite portable.
483 In contrast to the @code{hsearch} functions the @code{tsearch} functions
484 can be used with arbitrary data and not only zero-terminated strings.
486 The @code{tsearch} functions have the advantage that no function to
487 initialize data structures is necessary.  A simple pointer of type
488 @code{void *} initialized to @code{NULL} is a valid tree and can be
489 extended or searched.  The prototypes for these functions can be found
490 in the header file @file{search.h}.
492 @deftypefun {void *} tsearch (const void *@var{key}, void **@var{rootp}, comparison_fn_t @var{compar})
493 @standards{SVID, search.h}
494 @safety{@prelim{}@mtsafe{@mtsrace{:rootp}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
495 @c The tree is not modified in a thread-safe manner, and rotations may
496 @c leave the tree in an inconsistent state that could be observed in an
497 @c asynchronous signal handler (except for the caller-synchronization
498 @c requirement) or after asynchronous cancellation of the thread
499 @c performing the rotation or the insertion.
500 The @code{tsearch} function searches in the tree pointed to by
501 @code{*@var{rootp}} for an element matching @var{key}.  The function
502 pointed to by @var{compar} is used to determine whether two elements
503 match.  @xref{Comparison Functions}, for a specification of the functions
504 which can be used for the @var{compar} parameter.
506 If the tree does not contain a matching entry the @var{key} value will
507 be added to the tree.  @code{tsearch} does not make a copy of the object
508 pointed to by @var{key} (how could it since the size is unknown).
509 Instead it adds a reference to this object which means the object must
510 be available as long as the tree data structure is used.
512 The tree is represented by a pointer to a pointer since it is sometimes
513 necessary to change the root node of the tree.  So it must not be
514 assumed that the variable pointed to by @var{rootp} has the same value
515 after the call.  This also shows that it is not safe to call the
516 @code{tsearch} function more than once at the same time using the same
517 tree.  It is no problem to run it more than once at a time on different
518 trees.
520 The return value is a pointer to the matching element in the tree.  If a
521 new element was created the pointer points to the new data (which is in
522 fact @var{key}).  If an entry had to be created and the program ran out
523 of space @code{NULL} is returned.
524 @end deftypefun
526 @deftypefun {void *} tfind (const void *@var{key}, void *const *@var{rootp}, comparison_fn_t @var{compar})
527 @standards{SVID, search.h}
528 @safety{@prelim{}@mtsafe{@mtsrace{:rootp}}@assafe{}@acsafe{}}
529 The @code{tfind} function is similar to the @code{tsearch} function.  It
530 locates an element matching the one pointed to by @var{key} and returns
531 a pointer to this element.  But if no matching element is available no
532 new element is entered (note that the @var{rootp} parameter points to a
533 constant pointer).  Instead the function returns @code{NULL}.
534 @end deftypefun
536 Another advantage of the @code{tsearch} functions in contrast to the
537 @code{hsearch} functions is that there is an easy way to remove
538 elements.
540 @deftypefun {void *} tdelete (const void *@var{key}, void **@var{rootp}, comparison_fn_t @var{compar})
541 @standards{SVID, search.h}
542 @safety{@prelim{}@mtsafe{@mtsrace{:rootp}}@asunsafe{@ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
543 To remove a specific element matching @var{key} from the tree
544 @code{tdelete} can be used.  It locates the matching element using the
545 same method as @code{tfind}.  The corresponding element is then removed
546 and a pointer to the parent of the deleted node is returned by the
547 function.  If there is no matching entry in the tree nothing can be
548 deleted and the function returns @code{NULL}.  If the root of the tree
549 is deleted @code{tdelete} returns some unspecified value not equal to
550 @code{NULL}.
551 @end deftypefun
553 @deftypefun void tdestroy (void *@var{vroot}, __free_fn_t @var{freefct})
554 @standards{GNU, search.h}
555 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
556 If the complete search tree has to be removed one can use
557 @code{tdestroy}.  It frees all resources allocated by the @code{tsearch}
558 functions to generate the tree pointed to by @var{vroot}.
560 For the data in each tree node the function @var{freefct} is called.
561 The pointer to the data is passed as the argument to the function.  If
562 no such work is necessary @var{freefct} must point to a function doing
563 nothing.  It is called in any case.
565 This function is a GNU extension and not covered by the @w{System V} or
566 X/Open specifications.
567 @end deftypefun
569 In addition to the functions to create and destroy the tree data
570 structure, there is another function which allows you to apply a
571 function to all elements of the tree.  The function must have this type:
573 @smallexample
574 void __action_fn_t (const void *nodep, VISIT value, int level);
575 @end smallexample
577 The @var{nodep} is the data value of the current node (once given as the
578 @var{key} argument to @code{tsearch}).  @var{level} is a numeric value
579 which corresponds to the depth of the current node in the tree.  The
580 root node has the depth @math{0} and its children have a depth of
581 @math{1} and so on.  The @code{VISIT} type is an enumeration type.
583 @deftp {Data Type} VISIT
584 The @code{VISIT} value indicates the status of the current node in the
585 tree and how the function is called.  The status of a node is either
586 `leaf' or `internal node'.  For each leaf node the function is called
587 exactly once, for each internal node it is called three times: before
588 the first child is processed, after the first child is processed and
589 after both children are processed.  This makes it possible to handle all
590 three methods of tree traversal (or even a combination of them).
592 @vtable @code
593 @item preorder
594 The current node is an internal node and the function is called before
595 the first child was processed.
596 @item postorder
597 The current node is an internal node and the function is called after
598 the first child was processed.
599 @item endorder
600 The current node is an internal node and the function is called after
601 the second child was processed.
602 @item leaf
603 The current node is a leaf.
604 @end vtable
605 @end deftp
607 @deftypefun void twalk (const void *@var{root}, __action_fn_t @var{action})
608 @standards{SVID, search.h}
609 @safety{@prelim{}@mtsafe{@mtsrace{:root}}@assafe{}@acsafe{}}
610 For each node in the tree with a node pointed to by @var{root}, the
611 @code{twalk} function calls the function provided by the parameter
612 @var{action}.  For leaf nodes the function is called exactly once with
613 @var{value} set to @code{leaf}.  For internal nodes the function is
614 called three times, setting the @var{value} parameter or @var{action} to
615 the appropriate value.  The @var{level} argument for the @var{action}
616 function is computed while descending the tree by increasing the value
617 by one for each descent to a child, starting with the value @math{0} for
618 the root node.
620 Since the functions used for the @var{action} parameter to @code{twalk}
621 must not modify the tree data, it is safe to run @code{twalk} in more
622 than one thread at the same time, working on the same tree.  It is also
623 safe to call @code{tfind} in parallel.  Functions which modify the tree
624 must not be used, otherwise the behavior is undefined.  However, it is
625 difficult to pass data external to the tree to the callback function
626 without resorting to global variables (and thread safety issues), so
627 see the @code{twalk_r} function below.
628 @end deftypefun
630 @deftypefun void twalk_r (const void *@var{root}, void (*@var{action}) (const void *@var{key}, VISIT @var{which}, void *@var{closure}), void *@var{closure})
631 @standards{GNU, search.h}
632 @safety{@prelim{}@mtsafe{@mtsrace{:root}}@assafe{}@acsafe{}}
633 For each node in the tree with a node pointed to by @var{root}, the
634 @code{twalk_r} function calls the function provided by the parameter
635 @var{action}.  For leaf nodes the function is called exactly once with
636 @var{which} set to @code{leaf}.  For internal nodes the function is
637 called three times, setting the @var{which} parameter of @var{action} to
638 the appropriate value.  The @var{closure} parameter is passed down to
639 each call of the @var{action} function, unmodified.
641 It is possible to implement the @code{twalk} function on top of the
642 @code{twalk_r} function, which is why there is no separate level
643 parameter.
645 @smallexample
646 @include twalk.c.texi
647 @end smallexample
648 @end deftypefun