楼上的不是有序数组,如果是有序数组折半查找也是元素一次出现的角标位置;- public class Demo1 {
- public static void main(String[] args) {
- int[] arr = {1,2,4,5,6,6,8,9};
- System.out.println("index= " + halfSearch(arr,6));
- }
- public static int halfSearch(int[] arr,int num) {
- int min = 0,max = arr.length-1,mid = (max+min)/2;
- while(arr[mid] != num) {
- if(num > arr[mid]) {
- min = mid+1;
- }else if(num < arr[mid]) {
- max = mid-1;
- }
- if(min > max)
- return -1;
- else
- mid = (max+min)/2;
- }
- return mid;
- }
- }
复制代码 |