Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!mailrus!ncar!tank!gargoyle!chinet!john From: john@chinet.chi.il.us (John Mundt) Newsgroups: comp.lang.c Subject: Re: qsort - part of an array Keywords: qsort, array Message-ID: <1990Apr14.220814.6261@chinet.chi.il.us> Date: 14 Apr 90 22:08:14 GMT References: <19496@boulder.Colorado.EDU> Reply-To: john@chinet.chi.il.us (John Mundt) Distribution: usa Organization: Chinet - Chicago Public Access UNIX Lines: 63 In article <19496@boulder.Colorado.EDU> baileyc@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@admctr.chi.il.us *OR* fred@teacha.chi.il.us (312) 998-5007 (Day voice) || -432-8860 (Answer Mach) && -432-5386 Modem