Question

So, I have this array of objects with NSNumbers 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?

Was it helpful?

Solution

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]
    }];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top