java 折半查找
Posted hongxiao2020
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 折半查找相关的知识,希望对你有一定的参考价值。
public static void main(String[] args) { int[] arr = {0,1,2,3,4,5,6,7,8,9,10}; System.out.println(halfSearch_2(arr,5)); } public static int halfSearch_1(int[] arr,int key){ int min = 0, max = arr.length-1, mid = (min + max)/2; while (arr[mid] != key){ if ( key > arr[mid]) min = mid+1; else if (key < arr[mid]) max = mid-1; if (min>max) return -1; mid = (min + max)/2; } return mid; } public static int halfSearch_2(int[] arr,int key){ int min = 0, max = arr.length-1, mid; while (min<=max){ mid = (max+min)>>1; if ( key > arr[mid]) min = mid+1; else if (key < arr[mid]) max = mid-1; else return mid; } return -1; }
以上是关于java 折半查找的主要内容,如果未能解决你的问题,请参考以下文章