No. 47 - Search in a Rotation of an Array

参考:http://codercareer.blogspot.com/2013/03/no-47-search-in-rotation-of-array_31.html

Question: When some elements at the beginning of an array are moved to the end, it gets a rotation of the original array. Please implement a function to search a number in a rotation of an increasingly sorted array. Assume there are no duplicated numbers in the array.
For example, array {3, 4, 5, 1, 2} is a rotation of array {1, 2, 3, 4, 5}. If the target number to be searched is 4, the index of the number 4 in the rotation 1 should be returned. If the target number to be searched is 6, -1 should be returned because the number does not exist in the rotated array.

/* Copyleft: Ming Lin <minggr@gmail.com> */

#include <stdio.h>

int binary_search(int data[], int i, int j, int key)
{
	int m = (i+j)/2;

	if (i > j)
		return -1;

	if (data[m] == key)
		return m;
	else if (data[m] > key)
		return binary_search(data, i, m-1, key);
	else
		return binary_search(data, m+1, j, key);
}

int search(int data[], int i, int j, int key)
{
	int m = (i+j)/2;

	if (i > j)
		return -1;

	if (data[m] == key)
		return m;

	if (data[m] >= data[i]) {
		if (key >= data[i] && key <= data[m])
			return binary_search(data, i, m, key);
		else
			return search(data, m+1, j, key);
	}

	if (data[m] < data[i]) {
		if (key >= data[m] && key <= data[i])
			return binary_search(data, m, j, key);
		else
			return search(data, i, m-1, key);
	}
}

int main()
{
	int data[] = {30, 40, 50, 10, 20};
	int i = 0;
	int j = 4;
	int k;
	int n = 60;

	for (k = 0; k < n; k++)
		printf("Search %d, Index %d\n", k, search(data, i, j, k));

	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值