//
// NSArray+GBCalculation.h
// TCPUDPDemo
//
// Created by zxy on 2017/9/27.
// Copyright © 2017年 saint. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSArray(GBCalculation)
/**
数组基于条件的二分查找算法,判断数组中是否存在符合该条件的元素
@param condition condition description
@return return value description
*/
- (BOOL)fitterWithCondition:(BOOL(^)(id object))condition;
@end
//
// NSArray+GBCalculation.m
// TCPUDPDemo
//
// Created by zxy on 2017/9/27.
// Copyright © 2017年 saint. All rights reserved.
//
#import "NSArray+GBCalculation.h"
@implementation NSArray(GBCalculation)
- (BOOL)fitterWithCondition:(BOOL(^)(id object))condition{
if (self.count == 0) {
return NO;
}
int low = 0;
int height = (int)(self.count - 1);
int mid = (low + height)/2;
id obj = [self objectAtIndex:mid];
if (condition) {
BOOL fit = condition(obj);
if (fit) {
return YES;
}
NSArray *leftArr = [self subarrayWithRange:NSMakeRange(low, mid - low)];
if ([leftArr fitterWithCondition:condition]) {
return YES;
}
NSArray *rightArr = [self subarrayWithRange:NSMakeRange(mid + 1, height - mid)];
if ([rightArr fitterWithCondition:condition]) {
return YES;
}
return NO;
}
return NO;
}
@end