当前位置:   article > 正文

二分查找(非递归算法和递归算法)_数据结构查找二分查找递归、非递归算法

数据结构查找二分查找递归、非递归算法
非递归算法:
  1. package mytest;
  2. public class test {
  3. public static int BinarySearch(int low,int high,int[]arr,int x){
  4. int loc=-1;
  5. while(low<=high){
  6. int mid=(low+high)/2;
  7. if(x==arr[mid]){loc=mid;break;}
  8. else if(x<arr[mid])
  9. {high=mid-1;}
  10. else {low=mid+1;}
  11. }
  12. return loc;
  13. }
  14. public static void main(String[]args){
  15. int[]myArr={1,2,3,4,5,6};
  16. int loc=-1;
  17. loc=BinarySearch(0,myArr.length-1,myArr,15);
  18. if(loc==-1){System.out.println("Not found");}
  19. else{System.out.println("Find it!location is:"+loc);}
  20. }
  21. }
递归算法:
  1. package mytest;
  2. public class test {
  3. public static int BinarySearch(int low,int high,int[]arr,int x,int loc){
  4. if((low<=high)&&(loc==-1)){
  5. int mid=(low
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/896583
推荐阅读
相关标签
  

闽ICP备14008679号