Re: NSMutableArray sorting
Re: NSMutableArray sorting
- Subject: Re: NSMutableArray sorting
- From: Alastair Houghton <email@hidden>
- Date: Thu, 6 Sep 2007 18:26:05 +0100
On 6 Sep 2007, at 17:13, glenn andreas wrote:
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:
Gosh, that seems like a complicated way to do it :-)
I prefer having an array of indices; i.e.
int n, count = [first count];
for (n = 0; n < count; ++n)
[third addObject:[NSNumber numberWithInt:n]];
then
[third sortUsingFunction:indexedCompare context:NULL];
with
static int indexedCompare(id left, id right, void *context)
{
return [[first objectAtIndex:[left intValue]]
compare:[first objectAtIndex:[right intValue]]];
}
(This sorts the indices based on the contents of the first array).
Often you don't need to actually re-sort the arrays themselves
afterwards; you can just step through the index array and grab
objects at the indices you extract. You can also make this more
efficient, e.g. by using a C array or a C++ vector for your indices,
or by writing a specialised NSArray subclass specifically for holding
arrays of integers.
Kind regards,
Alastair.
--
http://alastairs-place.net
_______________________________________________
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