问题
So, I have this array of objects with NSNumber
s in it. I have a number of my own and I need to find a number in the array that's greater than my number by least margin.
How do I employ binary search for this?
The method : indexOfObject:inSortedRange:options:usingComparator
accepts the object as a parameter and I don't have it. How do I do the binary search with this condition but without an object?
回答1:
You need to supply an object - any object specifying the value of the item being searched. As long as the comparator knows how to extract the value, the indexOfObject:inSortedRange:options:usingComparator:
would return a proper value.
You need to specify NSBinarySearchingInsertionIndex
option to make the search return the position of the first item that's greater than your target value by the smallest amount, i.e. the insertion index for your new value.
NSNumber *target = ... // Your target number
int index = [sortedArray indexOfObject:target
inSortedRange:NSMakeRange(0, sortedArray.count)
options:NSBinarySearchingInsertionIndex
usingComparator:^(id lhs, id rhs) {
return [lhs compare:rhs]
}];
来源:https://stackoverflow.com/questions/21723915/binary-searching-nsarray-without-having-the-object-to-search-but-a-condition