二分查找的迭代实现

来源:互联网 发布:淘宝联盟还要人脸认证 编辑:程序博客网 时间:2024/05/18 12:39

【某互联网公司的笔试题一】

请实现以下函数int indexOf(int[] array,int target),给定一个循环有序的数组,请在这个数组中找到指定元素,找到的话返回下标,没有找到返回-1。

该数组的贴点是一个单调递增的数组向右循环移位形成的。例如,[4,8,13,20,23,34,41,52]经过向右循环移位有可能形成[23,34,41,52,4,8,13,20]。


public class SearchIndex {public static int indexOf(int[] array,int target){int len = array.length;int offset = 1;//数组偏移量for(int i = 0;array[i]<array[i+1];i++){offset = offset + 1;}int m;int left = 0;int right = len;while(left<right){m = left + (right-left)/2;if(array[m>=offset?m-offset:m+offset] == target){return m>=offset?m-offset:m+offset;}else if(array[m>=offset?m-offset:m+offset] > target){right = m;}else {left = m+1;}}return -1;}public static void main(String[] args) {int[] arr = {23,34,41,52,4,8,13,20};int index = indexOf(arr,34);System.out.println(index);}}



0 0
原创粉丝点击