How to perform binary search on NSArray?

前端 未结 5 712
失恋的感觉
失恋的感觉 2020-12-09 11:06

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. The use

5条回答
  •  误落风尘
    2020-12-09 11:20

    The second option is definitely the simplest. Ole Begemann has a blog entry on how to use the NSArray's indexOfObject:inSortedRange:options:usingComparator: method:

    NSArray *sortedArray = ... // must be sorted
    id searchObject = ...
    NSRange searchRange = NSMakeRange(0, [sortedArray count]);
    NSUInteger findIndex = [sortedArray indexOfObject:searchObject 
                                    inSortedRange:searchRange
                                          options:NSBinarySearchingFirstEqual
                                  usingComparator:^(id obj1, id obj2)
                                  {
                                      return [obj1 compare:obj2];
                                  }];
    

    See NSArray Binary Search

提交回复
热议问题