[plug] qsort

Bernard Blackham bernard at blackham.com.au
Sun Jun 9 15:48:38 WST 2002


James,

Are you talking about using the qsort function in C/C++? Though not
quite on topic, but here goes :)

	int some_array[50] = {...... fill in the array .....};
	qsort(some_array, 50, sizeof(int), int_cmp);

where int_cmp is your comparision function - takes two data elements
(they dont have to be ints), and returns 0 if they're equal, or a
negative or positive number depending if one is bigger or smaller
than the other. if you're not sorting strings you usually have to
define it yourself, eg:

	int int_cmp(const void* a, const void* b) {
		if (*(int*)a < *(int*)b) return -1;
		if (*(int*)a == *(int*)b) return 0;
		return 1; /* otherwise a>b */
	}

Note the awkward typecasting. You can do something similar for any
data type. strcmp will do strings for you.

http://www.cplusplus.com/ is a great resource (well it's the one I
recommend to people and they love it).

HTH,

Bernard.

On Sun, Jun 09, 2002 at 02:21:21PM +0800, James Elliott wrote:
> Hi
> 
> I would be obliged if anyone could give me an example using qsort.
> 
> I have read the man pages but I am obviously substituting the wrong
> information because I keep getting parse error messages.
> 
> I learn so much quicker from examples than from reading a description, but
> unfortunately the man pages rarely give examples.
> 
> Kind regards
> 
> James Elliott
> Ravensthorpe Computers
> ABN 34 305 232 710
> Tel:   08 9838 1043
> Fax:  08 9838 1049
> Cell:  0428 39 6052
> E-mail:  James.Elliott at wn.com.au
> Australia Post:
> PO Box 228, Ravensthorpe WA 6346
> 
> 
> 

-- 
 Bernard Blackham
 bernard at blackham.com.au
 Australian Linux Technical Conference 2003: http://conf.linux.org.au/



More information about the plug mailing list