1.算法思想
条件:1.必须采用顺序储存 2.有序排列
首先,将表中间位置记录下来,与查找元素进行进行比较。若相等,则查找成功;否则将其表以中间位置分成,前后两个子表,查找的元素小于中间位置元素,则进一步查找前一子表,否则进一步查找后一子表。循环或递归相同操作,直到查找相同返回序号,否则元素不存在。
2.效率
a.非递归
时间复杂度:T(n) = O(log2n)
空间复杂度:S(n) = O(1)
b.递归
时间复杂度:T(n) = O(log2n)
空间复杂度:S(n) = O(log2n)
3.实现
/**
* 顺序结构,有序
*/
public class Test2 {
public static void main(String[] args) {
int [] scoreArr = {1,2,3,4,5,6,7,8};
int score = 5;
//非递归
// int index = search(scoreArr, score);
//递归
int index = searchDG(scoreArr, score);
//输出结果
if (index == -1){
System.out.println("元素不存在");
}else {
System.out.println(score+"的索引是"+index);
}
}
/**
* 不使用递归
* T(n) = O(log2n)
* S(n) = O(1)
* @param arr
* @param key
* @return
*/
private static int search(int[] arr, int key) {
//指定low和high
int low =0;
int high = arr.length-1;
//折半查找
while (low<=high){
//求得mid
int mid = (low+high)/2;
//判断是否等于
if (key == arr[mid]){
return mid;
}else if (key>arr[mid]){
low = mid+1;
}else {
high = mid-1;
}
}
return -1;
}
/**
* 使用递归
* T(n) = O(log2n)
* S(n) = O(log2n)
* @param arr
* @param key
* @return
*/
private static int searchDG(int[] arr, int key) {
//指定low和high
int low =0;
int high = arr.length-1;
return searchDG(arr,key,low,high);
}
/**
* 详细操作
* @param arr
* @param key
* @param low
* @param high
* @return
*/
private static int searchDG(int[] arr, int key, int low, int high) {
//递归的结束条件
//1.没找到
if (low>high){
return -1;
}
//2.找到了
int mid = (low+high)/2;
if (key == arr[mid]){
return mid;
}else if (key<arr[mid]){
high = mid-1;
return searchDG(arr, key, low, high);
}else {
low = mid + 1;
return searchDG(arr, key, low, high);
}
}
}