文章目录
二分查找
二分查找的前提是有序的数组。
在本文中会使用递归来实现二分查找。
- 具体思路:
- 使用两个指针来确定数组范围。
left==0
以及right==a.length-1
。 - 通过比较
findVal
与midVal
的值,来确定是向右递归还是向左递归。 - 每次递归都会从当前数组中间(
mid
)开始,向左或向右。即实现二分。
代码实现
public class Binarysearch {
public static void main(String[] args) {
int a[]={0,1,2,3,4,5};
System.out.println(Binarysearch(a, 0, a.length - 1, 1));
}
public static int Binarysearch(int []a,int left,int right,int findVal){
int mid=(left + right)/2;
int midVal=a[mid];
//结束递归条件之一,当left>right时,代表没有找到该数。
if(left>right)
return -1;
if(findVal>midVal){ //向右递归。
return Binarysearch(a,mid+1,right,findVal);
}else if(findVal<midVal){ //向左递归。
return Binarysearch(a,left,mid-1,findVal);
}else if(findVal==midVal){ 如果执行此语句,代表已经找到当前元素在数组中的位置。
return mid;
}
return 0;
}
}
扩展/代码实现
问题引入: 如果此时数组中有多个重复的元素,想要查找到当前元素的所有下标,应该怎样实现?
- 思路分析:
可以利用二分查找找到当前元素的位置,由于元素在数组中顺序排列,即寻找当前元素的左边以及右边即可。
public static ArrayList<Integer> Binarysearchs(int []a,int left,int right,int findVal){
int mid=(left+right)/2;
int midVal=a[mid];
if(left>right)
return new ArrayList<>();
//创建ArrayList
ArrayList<Integer> arrayList=new ArrayList<>();
if(findVal>midVal) { //向右递归。
return Binarysearchs(a,mid+1,right,findVal);
}else if(findVal<midVal){ //向左递归。
return Binarysearchs(a,left,mid-1,findVal);
}else {
//向左遍历。
for(int temp=mid-1;temp>=0;temp--){
if(a[temp]==findVal){
arrayList.add(temp);
}else if(a[temp]!=findVal){
break;
}
}
arrayList.add(mid);
//向右遍历。
for(int temp=mid+1;temp<a.length;temp++){
if(a[temp]==findVal){
arrayList.add(temp);
}else if(a[temp]!=findVal){
break;
}
}
}
//对ArrayList进行排序。
Collections.sort(arrayList);
return arrayList;
}