Sorting&Searching 旋转数组二分法查找 @CareerCup

就是3种情况,写在注释里了


package Sorting_Searching;

/**
 * Given a sorted array of n integers that has been rotated an unknown number of
 * times, give an O(log n) algorithm that finds an element in the array. You may
 * assume that the array was originally sorted in increasing order.
 * 
 * EXAMPLE:
 * 
 * Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)
 * 
 * Output: 8 (the index of 5 in the array)
 * 
 * 译文:
 * 
 * 一个数组有n个整数,它们排好序(假设为升序)但被旋转了未知次, 即每次把最右边的数放到最左边。给出一个O(log n)的算法找到特定的某个元素。
 * 
 * 例子:
 * 
 * 输入:在数组(15 16 19 20 25 1 3 4 5 7 10 14)中找出5
 * 
 * 输出:8(5在数组中的下标)
 * 
 */
public class S11_3 {

	public static void main(String[] args) {
		int[] a = { 2, 3, 2, 2, 2, 2, 2, 2, 2, 2 };

		System.out.println(search(a, 0, a.length - 1, 2));
		System.out.println(search(a, 0, a.length - 1, 3));
		System.out.println(search(a, 0, a.length - 1, 4));
		System.out.println(search(a, 0, a.length - 1, 1));
		System.out.println(search(a, 0, a.length - 1, 8));
	}
	
	public static int search(int a[], int left, int right, int x) {
		int mid = (left + right) >> 1;
		if(x == a[mid]){		// 找到
			return mid;
		}
		if(left > right){
			return -1;
		}
		
		if(a[left] < a[mid]){		// 比如 Arrayl:  {10,  15,  20,  0,  5},找5
			if(x>=a[left] && x<=a[mid]){
				return search(a, left, mid-1, x);
			}else{
				return search(a, mid+1, right, x);
			}
		}else if(a[left] > a[mid]){		// 比如:Array2:  {50,  5,  20,  30,  40},找5
			if(a[mid]<=x && x<=a[right]){
				return search(a, mid+1, right, x);
			}else{
				return search(a, left, mid-1, x);
			}
		}else if(a[left] == a[mid]){	// 比如:{2,  2,  2,  3,  4,  2}
			if(a[mid] != a[right]){
				return search(a, mid+1, right, x);
			}else{
				int result = search(a, left, mid-1, x);
				if(result == -1){
					result = search(a, mid+1, right, x);
				}
				return result;
			}
		}
		return -1;
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值