I have an NSArray
with objects and a C array with doubles. I would like to sort the NSArray
objects based on the C array values.
The only way I could think of is below (based on this SO question):
NSArray *sortedArray;
sortedArray = [origArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b)
{
// Getting c array values at the same indices as the objects being compared
NSNumber *aValue = @(cArray[[origArray indexOfObject:a]]);
NSNumber *bValue = @(cArray[[origArray indexOfObject:b]]);
// Returning comparison result
return [aValue compare:bValue];
}];
But I think that the indexOfObject:
part is a bit costly. Is that so?
If so, is there any faster way of doing this?
Edit:
To provide a bit more context, this sorting is part of a fitness evaluation for an optimization algorithm. In my program, I have done a basic profiling and the fitness evaluation code turns out to be the bottleneck. As such, I am trying to optimize it.
Also, the number of elements in the arrays is expected to be from around 100 to 10k max.