首页 > 代码库 > 【JAVA】BinarySearch
【JAVA】BinarySearch
public class BinarySearch { static public int binarySearch(int[] arr, int num) { int l = 0, u = arr.length - 1; while (l <= u) { int curr = (l + u) / 2; if (arr[curr] == num) { System.out.println("the index is :" + curr); return curr; } if (arr[curr] > num) { u = curr - 1; } if (arr[curr] < num) { l = curr + 1; } } System.out.println("sorry,can't find the num:"+num); return -1; } static public void main(String args[]){ int[] arr = {2,3,4,5,11,22,33,44,88,99,101}; try{ if(binarySearch(arr, 44)!=7)throw new Exception(); if(binarySearch(arr, 2)!=0)throw new Exception(); if(binarySearch(arr, 101)!=10)throw new Exception(); if(binarySearch(arr, 332)!=-1)throw new Exception(); }catch(Exception ex){ ex.printStackTrace(); } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。