Quicksort to order array by business key?
I've an array of objects, the size of which I cannot predict. The contents of the array are model objects with properties of type nsstring and nsnumber.
I need to sort the arra开发者_高级运维y according to one of the properties, an nsnumber. How would you do it in objective-c/Cocoa? Implement quicksort or some other algorithm (which one)? Any libraries that handle that for you?
Update While the response below is correct, it only works on 10.6 and I'm targeting 10.5.
NSArray
has several sorting methods. Given your array, arr
,
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"numberProperty" ascending:YES];
NSArray *sortedArr = [arr sortedArrayUsingSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
will give you an array sorted (ascending) by @"numberProperty". Obviously, you'll have to substitute the name of the NSNumber
property in your model objects for @"numberProperty"
.
The sorting algorithm is not specified in NSArray
's sorting methods.
This is what I came up with:
NSArray *unsortedArray = [results allValues];
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc]
initWithKey:@"ordinalPosition"
ascending:YES]
autorelease];
NSArray *sortedArray = [unsortedArray
sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Use qsort()
from stdlib.h.
精彩评论