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
- No. 47 - Search in a Rotation of an Array
- Converting a array to an array of ranges in ruby
- No. 22 - Turning Number in an Array
- How to find number of a specific integer in an array of Fixnums ruby
- Matching Portions of A String to Elements of an Array in Ruby
- Count occurrences of a number in a sorted array with duplicates using Binary Search
- Sorting an array of hash in Ruby
- Thinking of Search in Rotated Sorted Array
- Distinguish between index of a decimal number and integer inside an array in Ruby?
- How do I sort an array of hashes by a value in the hash?
- [Leetcode] Search in a Rotated Sorted Array
- [刷题]Search in a Big Sorted Array
- search-in-a-big-sorted-array
- Search in a Big Sorted Array
- 【刷题】Search in a Big Sorted Array
- returns a number of second with no user activity (called in an OnTimer event of a TTimer component).
- Given an array of numbers, return array of products of all other numbers (no division)
- [LeetCode] Search in Rotated Sorted Array、Search for a Range、Search Insert Position、Search in Rotate
- java监听器模式
- 计算机视觉方面的代码(1)
- C# 窗口缩放 自定义控件缩放
- poj 1745——Divisibility
- 计算机视觉、机器学习相关领域论文和源代码大集合(转)
- No. 47 - Search in a Rotation of an Array
- 搭建RTEMS的交叉工具链-针对arm,powerpc,i386
- 关于rtsp server的连接保持问题
- mini2440 按键驱动添加输入子系统,让按键可以真正当做键盘一样用
- SGU 133. Border 最小区间覆盖
- 两年多没写博客了,重新写起来吧
- HDU 1698 Just a Hook
- Jquery Ajax方式访问WebService
- 浅析大型网站的架构