Date: Mon, 25 Feb 2013 19:08:47 +0000 (UTC) From: Giorgos Keramidas <keramida@FreeBSD.org> To: src-committers@freebsd.org, svn-src-all@freebsd.org, svn-src-stable@freebsd.org, svn-src-stable-9@freebsd.org Subject: svn commit: r247275 - stable/9/lib/libc/stdlib Message-ID: <201302251908.r1PJ8lrG085735@svn.freebsd.org>
next in thread | raw e-mail | index | archive | help
Author: keramida (doc committer) Date: Mon Feb 25 19:08:46 2013 New Revision: 247275 URL: http://svnweb.freebsd.org/changeset/base/247275 Log: MFH r247014, r247050 and r247051. 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 Christoph Mallon, christoph.mallon at gmx.de Approved by: gjb (mentor), remko (mentor) Modified: stable/9/lib/libc/stdlib/qsort.3 Directory Properties: stable/9/lib/libc/ (props changed) Modified: stable/9/lib/libc/stdlib/qsort.3 ============================================================================== --- stable/9/lib/libc/stdlib/qsort.3 Mon Feb 25 19:05:40 2013 (r247274) +++ stable/9/lib/libc/stdlib/qsort.3 Mon Feb 25 19:08:46 2013 (r247275) @@ -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
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?201302251908.r1PJ8lrG085735>