diff options
author | attilio <attilio@FreeBSD.org> | 2013-02-24 16:50:53 +0000 |
---|---|---|
committer | attilio <attilio@FreeBSD.org> | 2013-02-24 16:50:53 +0000 |
commit | cff31deb1a197b29ab976c135fdd01dfb6951a6a (patch) | |
tree | dbdcb15ce3419e48e823390b612d613ff00bd567 /lib/libc/stdlib | |
parent | b4e24f9126f7a4c80ce0c44f6b4230021089bc1e (diff) | |
parent | 084e5da56e3c4bc6f9c6ed314310a9b8af2c695b (diff) | |
download | FreeBSD-src-cff31deb1a197b29ab976c135fdd01dfb6951a6a.zip FreeBSD-src-cff31deb1a197b29ab976c135fdd01dfb6951a6a.tar.gz |
MFC
Diffstat (limited to 'lib/libc/stdlib')
-rw-r--r-- | lib/libc/stdlib/bsearch.3 | 8 | ||||
-rw-r--r-- | lib/libc/stdlib/qsort.3 | 42 |
2 files changed, 48 insertions, 2 deletions
diff --git a/lib/libc/stdlib/bsearch.3 b/lib/libc/stdlib/bsearch.3 index b3591f8e..25be842 100644 --- a/lib/libc/stdlib/bsearch.3 +++ b/lib/libc/stdlib/bsearch.3 @@ -32,7 +32,7 @@ .\" @(#)bsearch.3 8.3 (Berkeley) 4/19/94 .\" $FreeBSD$ .\" -.Dd April 19, 1994 +.Dd February 22, 2013 .Dt BSEARCH 3 .Os .Sh NAME @@ -71,6 +71,12 @@ less than, equal to, or greater than zero if the .Fa key object is found, respectively, to be less than, to match, or be greater than the array member. +See the +.Fa int_compare +sample function in +.Xr qsort 3 +for a comparison function that is also compatible with +.Fn bsearch . .Sh RETURN VALUES The .Fn bsearch diff --git a/lib/libc/stdlib/qsort.3 b/lib/libc/stdlib/qsort.3 index 0f7ef73..f34d260 100644 --- a/lib/libc/stdlib/qsort.3 +++ b/lib/libc/stdlib/qsort.3 @@ -32,7 +32,7 @@ .\" @(#)qsort.3 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd September 30, 2003 +.Dd February 20, 2013 .Dt QSORT 3 .Os .Sh NAME @@ -205,6 +205,46 @@ functions return no value. .Pp .Rv -std heapsort mergesort +.Sh EXAMPLES +A sample program that sorts an array of +.Vt int +values in place using +.Fn qsort , +and then prints the sorted array to standard output is: +.Bd -literal +#include <stdio.h> +#include <stdlib.h> + +/* + * Custom comparison function that can compare 'int' values through pointers + * passed by qsort(3). + */ +static int +int_compare(const void *p1, const void *p2) +{ + int left = *(const int *)p1; + int right = *(const int *)p2; + + return ((left > right) - (left < right)); +} + +/* + * Sort an array of 'int' values and print it to standard output. + */ +int +main(void) +{ + int int_array[] = { 4, 5, 9, 3, 0, 1, 7, 2, 8, 6 }; + const size_t array_size = sizeof(int_array) / sizeof(int_array[0]); + size_t k; + + qsort(&int_array, array_size, sizeof(int_array[0]), int_compare); + for (k = 0; k < array_size; k++) + printf(" %d", int_array[k]); + puts(""); + return (EXIT_SUCCESS); +} +.Ed .Sh COMPATIBILITY Previous versions of .Fn qsort |