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

算法-二分查找-非递归

程序员文章站 2022-06-17 19:49:10
...
package datastructure.binarysearch;

import java.util.ArrayList;

public class BinarySearch {

    public static void main(String[] args) {
        int[] array = {1,3,4,5,6,7,8,23,34,100};
        int i = binarySearch3(array, 100);
        System.out.println(i);

    }
    /**
     *
     * @param arr     升序数组
     * @param target   要找的数
     * @return       返回这个数的索引,没找到返回-1
     */


    public static int binarySearch3(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while(left <= right) {//退出的条件
            int mid = (left + right) / 2;
            if(arr[mid] == target) {
                return mid;
            }else if(arr[mid] < target) {
                left = mid + 1;
            }else {
                right = mid - 1;
            }
        }
        return -1;
    }
}

算法-二分查找-非递归
算法-二分查找-非递归