summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorkeramida <keramida@FreeBSD.org>2013-02-19 23:57:39 +0000
committerkeramida <keramida@FreeBSD.org>2013-02-19 23:57:39 +0000
commit5dce0c1384f698b3a27a82e72e3cbcf49b325404 (patch)
treea82693dd832d1606f225555225e29944e109ad40
parentd08a4b37f124c7155aa6d83f51bd25d2b295ea71 (diff)
downloadFreeBSD-src-5dce0c1384f698b3a27a82e72e3cbcf49b325404.zip
FreeBSD-src-5dce0c1384f698b3a27a82e72e3cbcf49b325404.tar.gz
Add a sample program that shows how a custom comparison function and
qsort(3) can work together to sort an array of integers. PR: docs/176197 Submitted by: Fernando, fapesteguia at opensistemas.com Approved by: gjb (mentor) MFC after: 1 week
-rw-r--r--lib/libc/stdlib/qsort.348
1 files changed, 47 insertions, 1 deletions
diff --git a/lib/libc/stdlib/qsort.3 b/lib/libc/stdlib/qsort.3
index 0f7ef73..83d9140 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
@@ -211,6 +211,52 @@ Previous versions of
did not permit the comparison routine itself to call
.Fn qsort 3 .
This is no longer true.
+.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>
+#include <string.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 = (int *)p1;
+ int *right = (int *)p2;
+
+ if (*left < *right)
+ return (-1);
+ else if (*left > *right)
+ return (1);
+ else
+ return (0);
+}
+
+/*
+ * 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 int array_size = sizeof(int_array) / sizeof(int_array[0]);
+ int k;
+
+ qsort(&int_array, array_size, sizeof(int), int_compare);
+ for (k = 0; k < array_size; k++)
+ printf(" %d", int_array[k]);
+ printf("\\n");
+ exit(EXIT_SUCCESS);
+}
+.Ed
.Sh ERRORS
The
.Fn heapsort
OpenPOWER on IntegriCloud