XM Magdalena 3D print, GGeorgy (3D)
LC #42 Pipers Alley

View Full Version : qsort problem

06-21-2009, 09:05 AM
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
boxArr = for i = -5 to 5 collect box pos:[0, i * 10, 0] width:4 length:4 height:4
format "BEFORE:\n"
print boxArr
qsort boxArr sortByAxisPos
format "\nAFTER:\n"
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...

06-21-2009, 11:56 AM
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]

06-24-2009, 05:45 AM
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 ?

CGTalk Moderation
06-24-2009, 05:45 AM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.