/* 二分查找:
- 查找元素對應的索引
- 前提:數組有序,這點特別重要!!!要求的數組一定要按照順序來的。
*/ -
package day13.searchAlgorithm; public class binarySearch { public static void main(String[] args){ int[] arr = {11,22, 33, 44, 55}; System.out.println(binarysearch(arr,11)); System.out.println(binarysearch(arr,22)); System.out.println(binarysearch(arr,33)); System.out.println(binarysearch(arr,44)); System.out.println(binarysearch(arr,55)); System.out.println(binarysearch(arr,66)); System.out.println(binarysearch(arr,77)); } private static boolean binarysearch(int[] arr, int num) { /** * 二分查找3點 * 1.確定 小中大 3個索引 * 2.判斷 中索引 的值是否等於 待查值,等於即返回true,不等於進入while循環 * 3.判斷 值的索引與中的索引的大小, 中大就大索引改爲中大索引-1, 中小就小索引改爲中大索引+1, 中大索引本身改爲大小索引之和的一半 * 4.當小索引大於大索引時返回false */ int max = arr.length - 1; int min = 0; int mid = (max + min) / 2; Boolean flag; while (arr[mid]!=num) { //當中間值 mid = (max + min) / 2; if (arr[mid] > num) { max = mid - 1; } else if (arr[mid] < num) { min = mid + 1; } if(min>max){ return false; } } return true; } }
總結:
-
二分查找關鍵在於數組中數字要有序,其次是確定好三個索引的大小關係。