This morning, I stumbled on this thread Why is it faster to process a sorted array than an unsorted array? and found it really interesting !
I wanted to give it a try in Objective-C and while implementing it, I faced the problem of sorting an array of integers. Hence the following question.
Let's consider an array of arraySize
integers, initialized with random values between 0 and 256:
int data[arraySize];
for (int c = 0; c < arraySize; ++c)
{
data[c] = arc4random() % 256;
}
I would like to sort this array and store the result in another array of integers. In C++ we could do something like :
std::sort(data, ...);
In Java, we would use :
Arrays.sort(data);
In Objective-C, I've done it like that :
int sortedData[arraySize];
NSArray* sortedArray = [NSArray array];
// Initialize the array to sort.
for ( int i = 0 ; i < arraySize ; ++i )
{
sortedArray = [sortedArray arrayByAddingObject:[NSNumber numberWithInt:data[i]]];
}
// Sort the array.
sortedArray = [sortedArray sortedArrayUsingSelector:@selector(compare:)];
// Copy the array back into a int[] array.
for (int c = 0; c < arraySize; ++c)
{
sortedData[c] = [sortedArray[c] intValue];
}
It works, but it seems to me it's a real pain and it's not optimized at all ! How could I improve this ?