二分法查找
二分法是当数据量很大时适宜采用,但是采用二分法的前提是,数据是有序不重复的。二分法又称折半查找,故名思意就是就是从中间开始比较查找,其基本思路是:假设数据是按升序排序的,对于给定值 x,从序列的中间位置开始比较,如果当前位置值等于 x,则查找成功;若 x 小于当前位置值,则在数列的前半段中查找;若 x 大于当前位置值则在数列的后半段中继续查找,直到找到为止。所以二分法查找的速度比较快,次数比较少,性能比较好;因此相对来说其删除和插入操作就不是那么灵活了。
先来一遍java的
package sample_test;
import java.util.Arrays;
public class ToFind {
public static void main(String[] args) throws Exception {
int[] arr = {2, 3, 5, 10, 15, 16, 18, 22, 26, 30, 32, 35, 41, 42, 43, 55, 56, 66, 67, 69, 72, 76, 82, 83, 88};
int[] arr2 = Arrays.copyOfRange(arr, 0, 5); //含头不含尾
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i]+" ");
}
System.out.println();
int positon = Arrays.binarySearch(arr, 55);
System.out.println("position is:"+positon);
ToFind tofind = new ToFind();
int index = tofind.search(arr, 8, 0, arr.length);
System.out.println(index);
}
public int search(int[] arr,int num,int start,int end) throws Exception{
int index = 0;
int mid = (end+start)/2;
if(num==arr[mid]) {
index = mid;
}else if(end-start==1 && arr[end]!=num && arr[start] !=num) {
throw new Exception("你要找的数不在这个数组里面");
}else if(num<arr[mid]) {
index = this.search(arr, num,start,mid);
}else if(num>arr[mid]) {
index = this.search(arr, num,mid,end);
}
return index;
}
}
再来一份python的
class ToFind(object):
def find(self, arr, num, start, end):
# 取中位数
mid = (start + end) // 2
if num == arr[mid]:
index = mid
elif end - start == 1 and arr[start] != num and arr[end] != num:
index = '你要找的数不在这个数组里面'
elif num < arr[mid]:
index = self.find(arr, num, start, mid)
elif num > arr[mid]:
index = self.find(arr, num, mid, end)
return index
if __name__ == '__main__':
arr = [2, 3, 5, 10, 15, 16, 18, 22, 26, 30, 32, 35, 41, 42, 43, 55, 56, 66, 67, 69, 72, 76, 82, 83, 88];
tofind = ToFind()
print(arr.index(55))
print(tofind.find(arr, 8, 0, len(arr)))