作者:香香画室_769 | 来源:互联网 | 2023-10-16 13:46
****二分查找递归方式与非递归方式*publicclassBinarySearch{递归方式publicvoidbinarySearch(inta[],intval,intl
public class BinarySearch {public void binarySearch(int a[],int val,int low,int high){int middle = (low+high)/2;if(low<high){if(a[middle]==val){System.out.println("找到元素下标:"+middle);}else if(val<a[middle]){binarySearch(a,val,low,middle-1);}else if(val>a[middle]){binarySearch(a,val,middle+1,high);}else{return ;}}return;}public void binarySearch2(int a[],int val){int low =0;int high = a.length-1;int middle = 0;while(low<=high){middle = (low+high)/2;if(val<a[middle]){high=middle-1;}else if(val>a[middle]){low=middle+1;}else{System.out.println("找到元素下标:"+middle);return;}}return;}public static void main(String[] args){BinarySearch binarySearch = new BinarySearch();int [] array = {10,23,4,3,2,5,1,2,623,92,23,23,234,2,34,234,234,2,10};BasicSort basicSort = new BasicSort();basicSort.basicSort(array);for(int n:array){System.out.print(" "+n);}
binarySearch.binarySearch2(array,234 );}
}