折半查找法的条件
1、存储结构一定是顺序结构
2、查找的表一定是按照关键字的大小有序排列
package com.qsw.datastructure.search;
public class TestSearchDemo02 {
public static void main(String[] args) {
//给定数组
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//给定要查找的值
int key = 10;
//完成查找
int index = search(array,key);
//输出结果
if(index == -1) {
System.out.println("没有此结果");
}else {
System.out.println(key+"的索引是:"+index);
}
}
public static int search(int[] arr,int key) {
int low = 0;
int high = arr.length - 1;
while(low <= high) {
int mid = (low + high)/2;
if(key == arr[mid]) {
return mid;
}else if(key < arr[mid]) {
high = mid - 1;
}else if(key > arr[mid]) {
low = mid + 1;
}
}
return -1;
}
}