Java之二分查找

package com.huaxin.exer;
/**
 * 二分查找
 * @author wtl
 * 前提:所查找的数组必须有序
 */

public class BinarySearch{
    public static void main(String[] args){
        
        int[] arr = new int[]{2,6,11,24,38,42,56,61,77,85,96};
        
        int head = 0;//初始受索引
        int end = arr.length - 1;//初始末索引

        int dest = 24;

        boolean isFlag = true;

        while(head <= end){
            
            int middle = (head + end) / 2;

            if(arr[middle] == dest){
                System.out.println("找到了,位置为:" + middle);
                isFlag = false;
                break;
            }else if(arr[middle] > dest){
                end = middle - 1;
            }else{//arr[middle] < dest
                head = middle + 1;
            }
        }
        if(isFlag){
            System.out.println("没有找到");
        }
    }
}

 

你可能感兴趣的:(Java之二分查找)