Has any one come with a solution to sort the CCArray? So far we can't use the sortUsingSelector, I think, so I had to do my own sorting method:
void merge(CCArray *a, CCArray *b, int lo, int mi, int hi)
{
int i, i1 = lo, i2 = mi + 1; // sub-array indexes
for (i = lo; i <= hi; i++) // for each element in destination b
{
if (i1 > mi) // if i1 is out of bounds, copy from i2
[b replaceObjectAtIndex: i withObject: [a objectAtIndex: i2++]];
else if (i2 > hi) // if i2 is out of bounds, copy from i1
[b replaceObjectAtIndex: i withObject: [a objectAtIndex: i1++]];
else if ((int)([[a objectAtIndex: i1] performSelector:compareFunction
withObject: [a objectAtIndex: i2]])
== NSOrderedAscending) // if (a[i1] < a[i2]) copy from i1
[b replaceObjectAtIndex: i withObject: [a objectAtIndex: i1++]];
else // if (a[i1] >= a[i2]) copy from i2
[b replaceObjectAtIndex: i withObject: [a objectAtIndex: i2++]];
}
// copy back b into a --> same as [a setArray: b];
for (i = lo; i <= hi; i++)
[a replaceObjectAtIndex: i withObject: [b objectAtIndex: i]];
}
void divideAndMerge(CCArray *a, CCArray *b, int lo, int hi)
{
int mi = (lo + hi) / 2; // calculate middle point
if (lo >= hi) return; // size is 1 or less --> done
divideAndMerge(a, b, lo, mi); // sort lower half
divideAndMerge(a, b, mi+1, hi); // sort upper half
merge(a, b, lo, mi, hi); // merge back sorted halves
}
void mergeSort(CCArray *array, SEL selector)
{
compareFunction = selector;
CCArray *buffer = [array copy]; // helper buffer
int n = [array count]; // number of items in array
divideAndMerge(array, buffer, 0, n-1); // sort everything
[buffer release]; // release the helper buffer
}
To use it, just:
mergeSort(objects, @selector(compare:));
I also had to add one new method to the latest version of CCArray:
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject {
[self insertObject:anObject atIndex:index];
[self removeObjectAtIndex: index+1];
}
Problem is, part of my bottleneck performance is on the sorting, so I'm wondering if there is a better way of doing this.