Binary searching NSArray without having the object to search but a condition

蓝咒 提交于 2019-12-11 11:41:54

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!