日志文章

2019-12-17 aflfte2011

二分法查找写法(折半检索)

package com.aflfte.array;

import java.util.Arrays;

/**
 * 二分法查找写法(折半检索)
 * @author root
 *
 */
public class TestBinarySearch {
    public static void main(String[] args) {
        int[] arr= {30,20,50,10,80,9,7,12,100,40,8};
        Arrays.sort(arr);//进行折半检索前数据必须先排好序
        System.out.println(Arrays.toString(arr));
        System.out.println(myBinarySearch(arr, 400));
        
        
    }
    public static int myBinarySearch(int[] arr,int value) {
        int low=0;
        int high=arr.length-1;
        while(low<=high) {
            int mid=(low+high)/2;
            if(value==arr[mid]) {
                return mid;
            }
            if(value>arr[mid]) {
                low=mid+1;
                
            }
            if(value<arr[mid]) {
                high=mid-1;
            }
        }
        return -1;
    }

}

« 包装类的使用方法 | 冒泡排序写法与优化»