Notifications
Clear all

[Closed] qsort problem

i’m trying to sort an array of objects based on their center.y value. the qsort function i’m using is a bit more versatile because you can supply the axis index if you want to sort in x or z. anyway the point is it’s not working and i can’t see why so i thought a fresh set of eyes could take a look at this and maybe see what’s wrong. try the code below and you’ll see what i’m talking about. WARNING: i call ‘delete objects’ in this snippit so save your scene and reset max etc before running it!

(
    	fn sortByAxisPos a b axis:2 =
    	(
    		case of
    		(
    			(a.center[axis] < b.center[axis]): -1
    			(b.center[axis] > a.center[axis]): 1
    			default: 0
    		)
    	)
    	
    	delete objects
    	clearListener()
    	boxArr = for i = -5 to 5 collect box pos:[0, i * 10, 0] width:4 length:4 height:4
    	format "BEFORE:
"
    	print boxArr
    	qsort boxArr sortByAxisPos
    	format "
AFTER:
"
    	print boxArr
    )

the result SHOULD be that the boxes are still in the same order as when boxArr is first created (ie. box01 – box11), however box01 is in the middle of the array when it should be the first item! The results for the actual objects i’m trying to sort are much worse, with no particular pattern and mostly in the wrong order. I’ve tried this in 2008 and 2009 and get the same problem.

EDIT: Solved
Ok i am a dope… i wasn’t supposed to switch around the variables a and b in the line:
(b.center[axis] > a.center[axis]): 1
swtiched them back and it works perfectly…

4 Replies

I know you resolved the issue, but I just wanted to add that for numeric comparisons, you can simplify the qsort function to this:

fn sortByAxisPos a b axis:2 = a.center[axis] - b.center[axis]

Martijn

that’s cool thanks Martijn. So i’m guessing that qsort just expects a positive or negative result or 0, rather than specifically -1, 1 and 0 ?

i can do it , thank you very much

Note that since max 2017 Update 1, there’s also a built-in Dictionary type.

Dictionary() -- empty dictionary of type #name
Dictionary (#integer | #name | #string) -- empty dictionary of the specified type
Dictionary {#(key, value)}+ -- one or more two-value arrays
Dictionary {key:value}+ -- one or more explicit key:value pairs
Dictionary {(DataPair key value)} -- one or more DataPair objects
<dictionary>[key] : get/set key value
<dictionary>.keys : Array, read-only