二分查找是一種查詢效率非常高的查找算法召耘。又稱折半查找谢谦。
二分查找的前提必須是有序的序列亲铡,優(yōu)點是查詢速度快,缺點是必須是有序序列
有序的序列竹挡,每次都是以序列的中間位置的數(shù)來與待查找的關鍵字進行比較镀娶,每次縮小一半的查找范圍,直到匹配成功揪罕。
畫圖分析:
思路:
A:定義最小索引梯码,最大索引
B:計算出中間索引
C:拿中間索引值和要查找的值作比較,
---- 相等:則直接返回
---- 大于:在右邊找
---- 小于:在左邊找
實現(xiàn)代碼如下:
/**
* 二分查找
*
*/
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {0,11,22,33,44,55,66,77,88};
System.out.println("66的索引位置:" + BinarySearch.binarySearch(arr, 88));
System.out.println("33的索引位置:" + BinarySearch.binarySearch(arr, 33));
System.out.println("100的索引位置:" + BinarySearch.binarySearch(arr, 100));
System.out.println("-----------------------------------");
System.out.println("66的索引位置:" + BinarySearch.binarySearch2(arr, 66));
System.out.println("33的索引位置:" + BinarySearch.binarySearch2(arr, 0));
System.out.println("100的索引位置:" + BinarySearch.binarySearch2(arr, 100));
System.out.println("-----------------------------------");
System.out.println("66的索引位置:" + BinarySearch.binarySearch3(arr, 66, 0, arr.length-1));
System.out.println("33的索引位置:" + BinarySearch.binarySearch3(arr, 33, 0, arr.length-1));
System.out.println("100的索引位置:" + BinarySearch.binarySearch3(arr, 100, 0, arr.length-1));
}
// 方式1
public static int binarySearch(int[] arr, int value) {
int min = 0;
int max = arr.length - 1;
int mid = (min + max) / 2;
while (arr[mid] != value) {
if (arr[mid] > value) {
max = mid - 1;
} else if (arr[mid] < value) {
min = mid + 1;
}
if (min > max) {
return -1;
}
mid = (min + max) / 2;
}
return mid;
}
// 方式2
public static int binarySearch2(int[] arr, int value) {
int min = 0;
int max = arr.length - 1;
int mid = (min + max) / 2;
while (min <= max) {
if (arr[mid] == value) {
return mid;
}
if (arr[mid] > value) {
max = mid - 1;
} else if (arr[mid] < value) {
min = mid + 1;
}
mid = (min + max) / 2;
}
return -1;
}
// 方式3 遞歸查找
public static int binarySearch3(int[] arr, int value, int min, int max) {
if (min > max) {
return -1;
}
int mid = (min + max) / 2;
if (arr[mid] > value) {
return binarySearch3(arr, value, min, mid-1);
} else if (arr[mid] < value) {
return binarySearch3(arr, value, mid+1, max);
}
return mid;
}
}
運行結果:
66的索引位置:8
33的索引位置:3
100的索引位置:-1
-----------------------------------
66的索引位置:6
33的索引位置:0
100的索引位置:-1
-----------------------------------
66的索引位置:6
33的索引位置:3
100的索引位置:-1
前兩種方式差不多好啰,都是通過循環(huán)轩娶。
第三種方式是通過遞歸,遞歸相對來說要占內存框往,推薦使用前兩種方式鳄抒。