如何执行上的NSArray二进制搜索? [英] How to perform binary search on NSArray?

查看:153
本文介绍了如何执行上的NSArray二进制搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是做一个二进制搜索最简单的方法是(已经)进行分类的NSArray

What is the simplest way to do a binary search on an (already) sorted NSArray?

我已经发现迄今一些可能的方式包括:

Some potential ways I have spotted so far include:

  1. 使用 CFArrayBSearchValues​​ 的(自提<一个href="https://developer.apple.com/library/mac/#documentation/CoreFOundation/Reference/CFArrayRef/Reference/reference.html">here) - 将这项工作在一个的NSArray
  2. 方法 indexOfObject:inSortedRange:选项:usingComparator: 的NSArray 的假设数组排序,需要一个选择采用类型的参数 NSBinarySearchingOptions - 这是否意味着它执行的二进制搜索?该<一href="https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">docs只是说:

  1. The use of CFArrayBSearchValues (mentioned here) - would this work on an NSArray?
  2. The method indexOfObject:inSortedRange:options:usingComparator: of NSArray assumes the array is sorted and takes an opts param of type NSBinarySearchingOptions - does this mean it performs a binary search? The docs just say:

通过使用给定的NSComparator块阵列中的元素进行比较返回对象的索引,在指定的范围内,

Returns the index, within a specified range, of an object compared with elements in the array using a given NSComparator block.

写我自己的二进制搜索法(沿东西线)。

  • Write my own binary search method (something along the lines of this).

    我要补充一点,我编程的iOS 4.3 +

    I should add that I am programming for iOS 4.3+

    在此先感谢。

    推荐答案

    1和2两个工作。 #2可能是更容易;它肯定没有任何意义的方法做任何事情比二进制搜索(如果范围是具有一定规模的,说了)等。你可以验证一个大阵,它只做少量的比较。

    1 and 2 will both work. #2 is probably easier; it certainly doesn't make sense for that method to do anything other than a binary search (if the range is above a certain size, say). You could verify on a large array that it only does a small number of comparisons.

    这篇关于如何执行上的NSArray二进制搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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