Re: NSMutableArray sorting
Re: NSMutableArray sorting
- Subject: Re: NSMutableArray sorting
- From: glenn andreas <email@hidden>
- Date: Thu, 6 Sep 2007 11:13:17 -0500
On Sep 6, 2007, at 10:52 AM, Alex Cohen wrote:
Hi, I have 2 NSMutableArray's and I need to sort one of them and I
need the
other one to follow along when the first one is sorted. Is there a
way to do
that using the array sorting functions?
Create a third array whose elements are first two array's elements
"zippered" together:
for (int i=0;i<[first count];i++) {
[third addObject: [NSArray arrayWithObjects: [first objectAtIndex:
i], [second objectAtIndex: i], nil]];
}
Sort that third array, using a function that basically extracts that
first element:
[third sortUsingFunction: zipperedCompare context: NULL];
...
int zipperedCompare(id left, id right, void *context)
{
return [[left objectAtIndex:0] compare: [right objectAtIndex: 1]];
}
Finally unzipper the third array back to the first two
for (int i=0;i<[third count];i++) {
[first replactObjectAtIndex: i withObject: [[third objectAtIndex: i]
objectAtIndex: 0]];
[second replactObjectAtIndex: i withObject: [[third objectAtIndex:
i] objectAtIndex: 1]];
}
One might be able to write a compare function that takes that second
array as the context parameter and infer how the first array is going
to get altered, but that probably either wouldn't work for all cases,
would require internal knowledge of the sorting routine (which might
break), and would require a whole lot of edge case testing to make
sure that you are keeping the array.
You could also just write your own sorting routine instead of using
the built in sorting methods.
Glenn Andreas email@hidden
<http://www.gandreas.com/> wicked fun!
quadrium | flame : flame fractals & strange attractors : build,
mutate, evolve, animate
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden