做一个合格的程序员总是绕不过算法这道坎,不管算法在实际运用如何,但总是一个程序员进步的必经之路,根据 《算法》逐一实现书中提到的算法
简单的二分查找法:这里使用到递归思想,尝试解决模块更小的子问题
swift:
<code>
//二分查找法
var array = [1,22,3,4,6,2]
func binarySearch(array:[Int],target:Int,start:Int,end:Int) ->Int {
if start > end {
return -1
}
let mid = start + (end - start)/2
if target > array[mid] {
return binarySearch(array, target: target, start:mid+1 , end: end)
}
else if target < array[mid] {
return binarySearch(array, target: target, start: start, end: mid-1)
}
else {
return mid
}
}
binarySearch(array, target: 3, start: 0, end: array.count-1)
</code>
输出 2
OC:
<code>
- (NSUInteger)binarySearch:(NSArray *)array target:(NSNumber *)target start:(NSUInteger)start end:(NSUInteger)end {
if (start > end) {
return -1;
}
NSUInteger mid = start + (end - start) / 2;
if (target > array[mid]) {
return [self binarySearch:array target:target start:mid+1 end:end];
}else if (target < array[mid]) {
return [self binarySearch:array target:target start:start end:mid-1];
}else {
return mid;
}
}
</code>