qsort - part of an array

Chris Torek chris at mimsy.umd.edu
Sat Apr 14 03:24:03 AEST 1990


In article <19496 at boulder.Colorado.EDU> baileyc at boulder.Colorado.EDU
(BAILEY CHRISTOPHER R) writes:
>I have an array, where only the end of it needs to be sorted (say the
>last 5 elements).  The part that confuses me the most is the comparand.

The compare function is never affected by the number of elements to be
compared: it operates pairwise.

>So, say my array is mapping[10] and I need to sort all the elements
>from mapping[4] to mapping [9].  How do I do this using qsort?

The full ANSI C prototype for qsort is

	void qsort(void *base, size_t nmemb, size_t size,
		int (*compare)(void *, void *));

>So, I would assume that my base would be mapping[4], that num would be
>10, and that width would be sizeof(int), but what about compare?

No: the address of the first of the contiguous sequence of objects
(`array') that you want sorted is `&mapping[4]', so `base' is

	(void *)&mapping[4]

The number of elements to be sorted is 6 (namely mapping-sub-4, 5, 6, 7,
8, and 9), so `nmemb' is (size_t)6.  The size of each element is
sizeof(int).  As for the compare function, you want one that returns
less-than, equal-to, or greater-than zero depending on whether the
integer at some location is less, equal, or greater than that at a
second location.  Qsort will pass only the location.  Thus one proper
comparison function is

	int mycompare(void *a, void *b) {
		return *(int *)a - *(int *)b;
	}

>In my case, if mapping is [10], then the highest number that can be stored
>in this array is 9, only the numbers 0 - 9 could be used in this array, and
>each one only once.  so mapping could look like: 1,3,5,9,8,2,7,6,0,4.

Qsort does not know or care that the elements are unique, bounded, etc.
All it wants is a contiguous sequence (`array') of objects of some fixed
size, along with a pointer to a function that, given the address of two
such objects, returns (consistently) a value <, ==, or > 0 depending
on whether those two objects are `in order', `equal: order unimportant',
or `out of order'.

In your case, since you know much more about your numbers, you could come
up with a more efficient sorting scheme.  For six numbers, however,
efficiency is not much of an issue.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list