二分查找的迭代實現

【某互聯網公司的筆試題一】

請實現以下函數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);
	}

}



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