算法背景:
binarySearch折半查找算法,也稱作二分法,是一種運(yùn)用于順序存儲(chǔ)結(jié)構(gòu)中的搜索算法,比如有序數(shù)組髓霞。
算法思想:
1.首先從有序數(shù)組中間值開(kāi)始搜索,如果該位置的值剛好等于要查找的值畦戒,則返回結(jié)果方库,搜索結(jié)束
2.當(dāng)要查找得值大于/小于中間元素,則在數(shù)組大于/小于中間元素的那一半?yún)^(qū)域查找障斋,然后重復(fù)步驟1的操作纵潦。
時(shí)間復(fù)雜度:o(n)
非遞歸算法:
/**
*非遞歸方法
*參數(shù) arr為int型有序數(shù)組{5,9,15,33,50,66,79}
* key為要查找的值
*返回值 返回值為目標(biāo)值索引
*/
public static int testBindarySearch(int[] arr, int key){
int low =0; //數(shù)組最小值的索引
int hight = arr.length-1; //數(shù)組最大值的索引
while(low<=hight){
int mid = (int) Math.floor((low+hight)/2);
if (key==arr[mid]){
return mid;
}else if(key>arr[mid]){
low = mid+1; //把最小索引變化到中間值+1的位置徐鹤,即數(shù)組的索引范圍為(mid+1,hight)
}else{
hight=mid-1; //把最大索引變化到中間值-1的位置,即數(shù)組的索引范圍為(low,mid+1)
}
}
return -1; //key值大于hight或小于low時(shí)
}
遞歸算法:(不推薦使用邀层,因?yàn)檫f歸算法是一種直接或者間接地調(diào)用自身的算法返敬,雖然代碼整潔,但運(yùn)行效率低寥院,且由于需要為局部量或返回點(diǎn)開(kāi)辟棧來(lái)存儲(chǔ)劲赠,容易造成棧溢出,報(bào)java.lang.StackOverflowError錯(cuò)誤)
/**
*遞歸方法
*參數(shù) arr為int型有序數(shù)組{5,9,15,33,50,66,79}
* key為要查找的值
*返回值 返回值為目標(biāo)值索引
*/
public static int testBindarySearch2(int[] arr,int key){
int low =0; //數(shù)組最小值的索引
int high= arr.length-1; //數(shù)組最大值的索引
if(low>high){return -1;}
int mid= (int) Math.floor((low+high)/2);
if(key==arr[mid]){
return mid;
}else if(key<arr[mid]){
high=mid-1;
return testBindarySearch2(arr,key);
}else{
low=mid+1;
return testBindarySearch2(arr,key);
}
}