1. 程式人生 > 實用技巧 >吳裕雄--天生自然ANDROID開發學習:2.6.1 PopupWindow(懸浮框)的基本使用

吳裕雄--天生自然ANDROID開發學習:2.6.1 PopupWindow(懸浮框)的基本使用

二分查詢【重點】

  前提

    陣列必須有序

  思路

    1.只要開始索引大於結束索引,就代表陣列中沒有該值

    2.中間索引位置元素大於目標值

        修改結束索引等於中間索引減1

    3.中間索引位置元素小於目標值

        修改索引等於中間索引加1

    4.中間索引位置元素等於目標值

        返回索引

    5.不確定迴圈次數

        while

        條件:開始索引小於等於結束索引

例圖:

程式碼:

public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};
//目標值
int userNumber = 70;
//呼叫方法,返回索引,沒有返回-1
int numberIndex = getBinarySearch(arr, userNumber);
System.out.println("值在陣列中索引是:" + numberIndex);
}

/**
* //二分查詢方法,返回索引,沒有返回-1
* @param arr
* @param userNumber
* @return
*/
private static int getBinarySearch(int[] arr, int userNumber) {
//開始索引
int startIndex = 0;
//結束索引
int endIndex = arr.length - 1;
//判斷是否存在(開始索引<=結束索引)
while (startIndex <= endIndex) {
//中間索引 = (開始+結束)÷2
int midIndex = (endIndex + startIndex) / 2;
//如果(中間索引位置元素>目標值)
if (arr[midIndex] > userNumber) {
//修改結束索引 = 中間索引 - 1
endIndex = midIndex - 1;
} else if (arr[midIndex] < userNumber) {
startIndex = midIndex + 1;
} else {
//否則 返回索引
return midIndex;
}
}
//沒有返回-1
return -1;
}