qsort - part of an array

John Mundt john at chinet.chi.il.us
Sun Apr 15 08:08:14 AEST 1990


In article <19496 at boulder.Colorado.EDU> baileyc at tramp.Colorado.EDU (BAILEY CHRISTOPHER R) writes:
>I'm not sure how to use qsort.  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.  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?
>

intcmp(*one, *two)		/* you provide the sorting function */
int *one, *two;			/* which gets pointersw to two members */
{				/* which qsort is comparing */
	return(*one < *two);
}

some_function()
{
int mapping[10];
	...
	qsort((char *)&mapping[4], 6, sizeof(int *), intcmp);
}
>So, I would assume that my base would be mapping[4], 
Right, but the address of mapping[4], either as I show it
above or mapping + 4

>that num would be 10, 
No, num is the number of items to be compared, mapping[4] to mapping[9],
which is six items

>and that width would be sizeof(int), 
No again.  mapping is an int pointer, and we want to move one int pointer
at a time.  

> but what about compare? ....
>How do I use compare?  All the examples I've seen the compare doesn't make
>sense to me. 
the compare is simply a function that returns less than zero if the
first item is less than the second, 0 if they are the same, or more than
zero if the first item is greater than the second.  Since you write the
function, the decision as to what is greater or less is arbitrary.  You
can use standard library functions once removed too, so if you did a 
sort of strings passed to main, you could do

int strcmp();
int strcmp2(s1, s2)
char **s1, **s2;
{
	return(strcmp(*s1, *s2));
}

main(argc, argv)
int argc;
char **argv;
{
	(void)qsort((char *) argv, argc, sizeof(char **), strcmp2);
	while (*argv)
		(void)printf("%s\n", *argv++);
}

-- 
---------------------
John Mundt   Teachers' Aide, Inc.  P.O. Box 1666  Highland Park, IL
john at admctr.chi.il.us *OR* fred at teacha.chi.il.us
(312) 998-5007 (Day voice) || -432-8860 (Answer Mach) && -432-5386 Modem  



More information about the Comp.lang.c mailing list