二进制搜索NSArray而没有要搜索的对象,但有条件 [英] Binary searching NSArray without having the object to search but a condition

查看:56
本文介绍了二进制搜索NSArray而没有要搜索的对象,但有条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有这个包含NSNumber的对象数组.我有一个自己的数字,我需要在数组中找到一个至少比我的数字大的数字.

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?

方法:indexOfObject:inSortedRange:options:usingComparator接受对象作为参数,但我没有.在没有对象的情况下如何执行二进制搜索?

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?

推荐答案

您需要提供一个对象-任何指定要搜索的项目值的对象.只要比较器知道如何提取该值,indexOfObject:inSortedRange:options:usingComparator:就会返回适当的值.

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.

您需要指定NSBinarySearchingInsertionIndex选项,以使搜索返回比目标值大最小量的第一项的位置,即新值的插入索引.

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]
    }];

这篇关于二进制搜索NSArray而没有要搜索的对象,但有条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆