[Midnightbsd-cvs] src [8823] trunk/lib/libc/stdlib/qsort.3: add a sample program for qsort(3)

laffer1 at midnightbsd.org laffer1 at midnightbsd.org
Sun Sep 25 23:44:10 EDT 2016


Revision: 8823
          http://svnweb.midnightbsd.org/src/?rev=8823
Author:   laffer1
Date:     2016-09-25 23:44:09 -0400 (Sun, 25 Sep 2016)
Log Message:
-----------
add a sample program for qsort(3)

Modified Paths:
--------------
    trunk/lib/libc/stdlib/qsort.3

Modified: trunk/lib/libc/stdlib/qsort.3
===================================================================
--- trunk/lib/libc/stdlib/qsort.3	2016-09-26 03:43:33 UTC (rev 8822)
+++ trunk/lib/libc/stdlib/qsort.3	2016-09-26 03:44:09 UTC (rev 8823)
@@ -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 @@
 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



More information about the Midnightbsd-cvs mailing list