Binary search in a NSMutableArray of NSDictionary
Howdy all! First question here, so please be gentle :). I'm somewhat familiar with Objective-C but am having some problems with the particulars. In short, I want to know how I can performa a binary search on a NSMutableArray of NSDictionaries, and in that search, look for partial string syntax. I have an NSMutableArray of NSDictionaries, where the array is a contact list and each NSDictionary is one contact (with four pieces of information). I managed to sort the array using
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:type ascending:YES];
[addressBook sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
where the key is the user-supplied key in the dictionary. Part of the functionality of the program is to perform prefix searches on each piece of data in the individual contacts.
So while I have found -indexOfObject:inSortedRange:options:usingComparator: (and in particular, this post, I can't figure out how to instruct the search to both search for the prefix of a string and how to implement the block syntax for the search itself.
I tried this - but I just get the ever so helpful "Expected expression" error, as I'm assuming I cannot substitute indexOfObjectPassingTest for indexOfObject.
unsigned index2 = [addressBook
indexOfObjectPassingTest:<#^BOOL(i开发者_开发百科d obj, NSUInteger idx, BOOL *stop)predicate#>:^(id obj, NSUInteger idx, BOOL *stop)
inSortedRange:NSMakeRange(0, [addressBook count])
options:NSBinarySearchingFirstEqual
usingComparator:(NSComparator^(id obj1, id obj2)];
I'd appreciate any assistance in getting -indexOfObject:inSortedRange:options:usingComparator: to work, or if someone has another suggestion for binary search on an NSArray of NSDictionaries, I'm all ears.
(And yes, while this is for an algorithms assignment, it's programming language agnostic. I am trying to maximize speed, so my thought had been to the array each time you are searching on it. I had also thought of making copies of the array sorted for each dictionary key, but because we are dealing with large CSV files, that seemed a bit excessive. So any other Mac-specific asymptotic hints would be MUCH appreciated, as it's often hard to find that in Apple's documentation.)
Foundation framework does not let you explicitly specify binary search on NSArray unless you already have the object and looking for the index value (well obviously arrays are not always sorted).
One thing you could do is to get an array of values for the specified key, convert it to an CFArray (for free) and use Core Foundation's CFArrayBSearchValue function.
The other thing I would do is to add a category to NSArray which takes a block-formed comparator and implements binary search algorithm.
精彩评论