今天给大家带来IOS开发算法 二分查找【附代码】,希望能够帮助到大家。
/** 二分查找法只适用于已经排好序的查找 */ - (NSInteger)dichotomySearch:(NSArray *)array target:(id)key { NSInteger left = 0; NSInteger right = [array count] - 1; NSInteger middle = [array count] / 2; while (right >= left) { middle = (right + left) / 2; if (array[middle] == key) { return middle; } if (array[middle] > key) { right = middle - 1; }else if (array[middle] < key) { left = middle + 1; } } return -1; }