二分查找的迭代实现

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

请实现以下函数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);
	}

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章