二分查找 Day08

package com.sxt.arraytest2;
/*
 * 二分查找 前提:有序
 */
public class TestBinarySearch {
    public static void main(String[] args) {
        //待查找序列
        int[] arr = {1,3,5,7,9,13};
        //待查目标 
        int ele = 13;
        BSearch(arr,ele);
        
    }

    private static void BSearch(int[] arr, int ele) {
        //若存在存入index 否则index为初始值-1
        int index = -1;
        //开始的下标
        int start = 0;
        //结束的下标
        int end = arr.length-1;
        while(start <= end){//循环条件
            int mid = (start + end)/2;
            if(arr[mid] == ele){
                index = mid;
                break;//若找到 跳出循环!!
            }else if(arr[mid] > ele){
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }
        if(index == -1){
            System.out.println("不存在元素"+ele);
        }else{
            System.out.println("该元素的下标:"+index);
        }
    }
}

 

posted @ 2017-04-22 17:09  清风追梦enjoy  阅读(151)  评论(0编辑  收藏  举报