算法——二分查找
二分查找
对于一个有序的可迭代序列,查找一个元素时,每次都猜中间的那个数,这样一次可以排除掉一半的数据
Python版本
def main(ary, item):
low = 0
high = len(ary) - 1
while low <= high:
mid_index = (low+high) // 2 # 中间索引位
mid_value = ary[mid_index] # 中间值
if mid_value == item:
return mid_index
elif mid_value < item:
low = mid_index + 1
else: # mid_value > item:
high = mid_index - 1
return None
ary = [1, 3, 4, 56, 78, 99]
print(main(ary, 3)) # 1
Java版本
public class More {
public static void main(String[] args) {
Integer[] ary = new Integer[] {1, 3, 4, 56, 78, 99};
int item = 3;
int low = 0;
int high = ary.length - 1;
while (low <= high) {
int midIndex = (low + high) / 2;
int midValue = ary[midIndex];
if (midValue == item) {
System.out.println(midIndex);
break;
} else if (midValue < item) {
low = midIndex + 1;
} else {
high = midIndex - 1;
}
}
}
}