题目:把一个数组最开始的若干各元素搬到数组的末尾,称之为旋转数组,输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}是数组{1,2,3,4,5}的一个旋转,该数组的最小值为1;
1 #include<stdio.h> 2 int MinInOrder(int r[], int p1, int p2) 3 { 4 int result = r[p1]; 5 for (int i = p1 + 1; i <= p2; i++) 6 { 7 if (r[i] < result) 8 result = r[i]; 9 } 10 return result; 11 } 12 int Min(int r[], int length) 13 { 14 if (r == NULL || length <= 0) 15 return 0; 16 int p1 = 0; 17 int p2 = length - 1; 18 int mid = p1; 19 while (r[p1] >= r[p2]) 20 { 21 if (p2 - p1 == 1) 22 { 23 mid = p2; 24 break; 25 } 26 mid = (p1 + p2) / 2; 27 if (r[p1] == r[p2] && r[mid] == r[p2]) 28 return MinInOrder(r, p1, p2); 29 if (r[mid] >= r[p1]) 30 p1 = mid; 31 else if (r[mid] <= r[p2]) 32 p2 = mid; 33 } 34 return r[mid]; 35 } 36 37 int main() 38 { 39 int a[8] = { 1, 1, 1, 0, 1 }; 40 printf("%d\n", Min(a, 5)); 41 return 0; 42 }
时间: 2024-10-14 05:49:58