折半查找

循环终止的条件是 最大索引max > 最小索引min

public class BinarySearchArray {

    public static void main(String[] args) {
        int[] array = {1, 3, 4, 6, 8, 9, 12, 13, 16, 19};
        int num = 5;
        
        int result = binarySearch(array,num);
        if(result == -1) {
            System.out.println("没找到");
        }else {
            System.out.println("找到了,该元素在数组中的索引为" + result);
        }

    }
    
    public static int binarySearch(int[]arr, int num) {
        int min_index = 0;
        int max_index = arr.length-1;
        int mid_index = 0;
        while(min_index <= max_index){
            mid_index = (min_index + max_index)/2;
            if(num > arr[mid_index]) {
                min_index = mid_index + 1;
            }else if(num < arr[mid_index]) {
                max_index = mid_index -1;
            }else {
                return mid_index;
            }
        }
        return -1;
        
    }

}

 

python的三套解法

lst = [11, 22, 33, 44, 55, 66, 77, 88, 99]  # 有序列表
n = 33  # 查找数字33是否在有序列表中

print("===========================循环+算法===================================")
left = 0  # 列表索引 左侧首端下标
right = len(lst)-1  # 列表索引 右侧尾端下标
count = 1  # 记录比较的次数

while left <= right:
    middle = (left + right) // 2

    if n > lst[middle]:
        left = middle + 1
    elif n < lst[middle]:
        right = middle - 1
    else:
        print("找到了,共经历了%d轮查找" % count)
        print("在列表中索引下标为:", middle)
        break
    count = count + 1
else:
    print("不存在")


print("============================利用递归===================================")
nlst = [11, 22, 33, 44, 55, 66, 77, 88, 99]


def binary_search(left, right, n, dp):
    dp = dp + 1
    if right < left:
        print("全部找完了")
        return -1   # 递归的出口

    middle = (left + right) // 2
    if n > nlst[middle]:
        left = middle + 1
    elif n < nlst[middle]:
        right = middle - 1
    else:
        print("找到了,且共经历了%d次查找" % dp)
        return middle

    return binary_search(left, right, n, dp)  # 递归的入口


site = binary_search(0, len(nlst)-1, 77, 0)
print("在列表中索引下标为:", site)


print("============================利用递归===================================")
num_list = [11, 22, 33, 44, 55, 66, 77, 88, 99]


def binarySearch(num_list, n):
    left = 0
    right = len(num_list) - 1
    middle = (left + right) // 2

    if right <= 0:
        print("不断切列表直至最终也没有找到")

    if n > num_list[middle]:
        left = middle + 1
        num_list = num_list[left:]
    elif n < num_list[middle]:
        right = middle - 1
        num_list = num_list[:right]
    else:
        print("找到了")
        return  # 由于列表不断切片生成新列表,每次查找都是在新列表中,因此无法返回被找到数在最初列表中的索引位置

    binarySearch(num_list, n)


binarySearch(num_list, 88)
View Code

 

posted @ 2020-04-24 22:24  CherryYang  阅读(156)  评论(0)    收藏  举报