No. 47 - Search in a Rotation of an Array

来源:互联网 发布:胡鞍钢为什么得宠知乎 编辑:程序博客网 时间:2024/05/17 22:41

参考: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);elsereturn 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);elsereturn 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);elsereturn 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