查找算法_02_二分查找(附java和python语言的编程实现)

二分查找

基本思想

二分查找是基于有序表查询的一种查找算法,二分的是意思是每次缩小查找的范围来加快查找速度,前提是查找的数组一定的得是有序的

图解示例

查找算法_02_二分查找(附java和python语言的编程实现)_第1张图片

编码提要

编码的过程中,注意向左向右递归时,相应参数的设定

java语言编程实现

package com.cc.searchcollection;

/**
 * @Classname Code_02_BinarySearch
 * @Description TODO
 * @Date 2020/3/3 13:50
 * @Created by dreamBreathing
 */
public class Code_02_BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 12};
        int resultIndex = binarySearch(arr, 0, arr.length-1, 7);
        if (resultIndex != -1) {
            System.out.println("找到啦,下标为" + resultIndex);
        } else {
            System.out.println("数组中没有目标数");
        }
        System.out.println(resultIndex);
    }

    public static int binarySearch(int[] arr, int left, int right, int targetVal) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];
        if (targetVal > midVal) {//向右递归查找
            return binarySearch(arr, mid + 1, right, targetVal);
        } else if (targetVal < midVal) {//向左递归查找
            return binarySearch(arr, left, mid - 1, targetVal);
        } else {
            return mid;
        }
    }
}

python语言编程实现

# -- coding: utf-8 --
# @Time : 2020/3/10 14:27
# @Author : dreamBreathing
# @File : binarysearch.py
# @Software: PyCharm


def binary_search(tag_list, left, right, target):
    if left > right:
        return -1
    mid = (left + right) // 2
    mid_value = tag_list[mid]
    if target > mid_value:
        return binary_search(tag_list, mid + 1, right, target)
    elif target < mid_value:
        return binary_search(tag_list, left, mid - 1, target)
    else:
        return mid


if __name__ == "__main__":
    list1 = [1, 3, 5, 7, 9, 12]
    result_index = binary_search(list1, 0, len(list1) - 1, 7)
    if result_index != -1:
        print("找到啦,下标为" + str(result_index))
    else:
        print("数组中没有目标元素")

你可能感兴趣的:(数据结构与算法)