欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线性查找、二分法 JAVA、Python

程序员文章站 2024-03-19 21:31:40
...

线性查找:
JAVA

public class TestSearch {
    public static void main(String[] args){
        int[] arr =new int[]{1,2,5,4,6,8,7,0};
        int target = 0;
        int index = -1;

        for (int i =0;i<arr.length;i++){
            if (arr[i]==target){
                index = i;
                break;
            }
        }
        System.out.println("index:"+index);
    }
}

Python

def linearsearch(arr,value):
    index = -1
    for i in range(len(arr)):
        if arr[i] == value:
            index = i
            break
    print(index)
num_list = [5,9,7,1,3,6]
linearsearch(num_list,6)

二分法
JAVA

public class BinarySearch {
    public static void main(String[] args){
        int[] arr = new int[]{1,2,3,4,5,6,7,8,9};
        int target = 10;
        int begin = 0;
        int end = arr.length-1;
        int index = -1;

        while (begin<=end){
            int mid = (begin + end)/2;
            if (arr[mid]==target){
                index=mid;
                break;
            }else if(arr[mid]>target){
                end = mid-1;
            }else {
                begin = mid +1;
            }
        }
        System.out.println("index:"+index);
    }

}

Python

def BinearSearch(arr,target):
    begin = 0
    end = len(arr)-1
    index = -1
    while begin <= end:
        mid = int((begin + end)/2)
        if arr[mid] == target:
            index = mid
            break
        elif arr[mid] > target:
            end = mid -1
        else:
            begin = mid +1
    print(index)

num_list = [1,2,3,4,5,6,7,8,9]
BinearSearch(num_list,9)