当前位置:   article > 正文

Java二分查找代码

java二分查找

二分查找需要首先 对数组排序(略)

  1. class HalfSearch {
  2. public static void main(String[] args) {
  3. int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
  4. int index = halfSearch(arr, 8);
  5. System.out.println(index);
  6. }
  7. public static int halfSearch(int[] arr, int target) {
  8. int max = arr.length - 1;
  9. int min = 0;
  10. int mid = (max + min) / 2;
  11. while(max >= min) {
  12. if(target > arr[mid]) {
  13. min = mid + 1;
  14. } else if(target < arr[mid]) {
  15. max = mid - 1;
  16. } else {
  17. return mid;
  18. }
  19. mid = (max + min) / 2;
  20. }
  21. return -1;
  22. }
  23. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/977781
推荐阅读
相关标签
  

闽ICP备14008679号