How to perform binary search on NSArray?

前端 未结 5 678
失恋的感觉
失恋的感觉 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:22

    //Method to pass array and number we are searching for.
    - (void)binarySearch:(NSArray *)array numberToEnter:(NSNumber *)key{
    
    
        NSUInteger  minIndex = 0;
        NSUInteger  maxIndex = array.count-1;
        NSUInteger  midIndex = array.count/2;
    
    
        NSNumber *minIndexValue = array[minIndex];
        NSNumber *midIndexValue = array[midIndex];
        NSNumber *maxIndexValue = array[maxIndex];
    
        //Check to make sure array is within bounds
        if (key > maxIndexValue || key < minIndexValue) {
            NSLog(@"Key is not within Range");
            return;
        }
    
        NSLog(@"Mid indexValue is %@", midIndexValue);
    
        //If key is less than the middleIndexValue then sliceUpArray and recursively call method again
        if (key < midIndexValue){
            NSArray *slicedArray = [array subarrayWithRange:NSMakeRange(minIndex, array.count/2)];
            NSLog(@"Sliced array is %@", slicedArray);
            [self binarySearch:slicedArray numberToEnter:key];
    
         //If key is greater than the middleIndexValue then sliceUpArray and recursively call method again
        } else if (key > midIndexValue) {
            NSArray *slicedArray = [array subarrayWithRange:NSMakeRange(midIndex+1, array.count/2)];
            NSLog(@"Sliced array is %@", slicedArray);
            [self binarySearch:slicedArray numberToEnter:key];
    
        } else {
          //Else number was found
            NSLog(@"Number found");
        }
    
    }
    
    
    //Call Method
    
    @interface ViewController ()
    @property(nonatomic)NSArray *searchArray;
    @end
    
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    //Initialize the array with 10 values
        self.searchArray = @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10];
    
    //Call Method and search for any number
        [self binarySearch:self.searchArray numberToEnter:@5];
        // Do any additional setup after loading the view, typically from a nib.
    }
    

提交回复
热议问题