//旋转数组的最小数字 //题目:把一个数组最開始的若干个元素搬到数组的末尾。我们称之为数组的旋转。//输入一个递增排序的数组的一个旋转。输出旋转数组中的最小元素。
//比如:数组{3。4,5,1,2}为{1,2。3。4。5}的一个旋转,最小元素是1。
#include <stdio.h> #include <assert.h> int min_equ(int *src, int left, int right) { int i = 0; int ret = src[left]; assert(src != NULL); for (; i < right; ++i) { if (ret >src[i]) return src[i]; } return ret; } int find_a_num(int *src, int len) { int left = 0; int right = len - 1; int mid = left; assert(src != NULL); while (src[left] >= src[right]) { if (right - left == 1) { mid = right; break; } mid = (left + right) / 2; if (src[left] == src[right] && src[mid] == src[right]) { return min_equ(src, left, right); } if (src[mid]>src[left]) { left = mid; } if (src[mid]<src[right]) { right = mid; } } return src[mid]; } int main() { int src[] = { 3, 4, 5, 1, 2 }; int dst[] = { 1, 0, 1, 1, 1 }; int len = sizeof(src) / sizeof(src[0]); int len1 = sizeof(dst) / sizeof(dst[0]); printf("%d ", find_a_num(src, len)); printf("%d ", find_a_num(dst, len1)); return 0; }