Object-C代码练习【二分法查找】

//
//  main.m
//  BinarySearch
//
//  Created by on 14-9-30.
//  Copyright (c) 2014年 apple. All rights reserved.
//

//二分法查找
#import <Foundation/Foundation.h>
#import "BinarySearch.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithCapacity:10];
        for (int i = 10; i < 50; i++) {
            [mutableArray addObject:[NSNumber numberWithInteger:i]];
        }
        
        BinarySearch *binarySearch = [[BinarySearch alloc] init];
        NSLog(@"%ld", (long)[binarySearch binarySearchIndex:[NSNumber numberWithInteger:33] arrayBySearch:mutableArray]);
    }
    return 0;
}
//
//  BinarySearch.h
//  BinarySearch
//
//  Created by on 14-9-30.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface BinarySearch : NSObject

- (NSInteger) binarySearchIndex: (NSNumber *) key arrayBySearch: (NSMutableArray *) mutableArray;

@end
//
//  BinarySearch.m
//  BinarySearch
//
//  Created by on 14-9-30.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "BinarySearch.h"

@implementation BinarySearch

- (NSInteger) binarySearchIndex: (NSNumber *) key arrayBySearch: (NSMutableArray *) mutableArray {
    NSInteger min = 0;
    NSInteger max = (NSInteger)([mutableArray count] - 1);
    
    while (min <= max) {
        NSInteger mid = (min + max) / 2;
        
        if (key > [mutableArray objectAtIndex:mid]) {
            min = mid + 1;
        } else if (key < [mutableArray objectAtIndex:mid]) {
            max = mid - 1;
        } else if (key == [mutableArray objectAtIndex:mid]) {
            return mid;
        }
    }
    return -1;
} // binarySearchIndex

@end


你可能感兴趣的:(Object-C代码练习【二分法查找】)