2 考虑到事先是排好序的,所以我们能够使用二分查找法来实现这个操作,仅仅只是是这个二分查找法是传统二分查找法的变种。
这里我们仅仅要考虑下面3种情况。
<1>数组先递增再递减,中值大于左值,那么此时的最小值就处于数组的右半部。
<2>数组先递增再递减,中值小于左值,那么此时的最小值就处于数组的左半部。
<3>数组单调递增,此时的最小值就是数组的首元素。
3 程序实现
依据解析中2的思想,採取二分查找法的程序例如以下所看到的:
#include <iostream> using namespace std; int getInvertNumber(int arr[],int nLength); void main() { int arr[] = {1,2,3,4,5,6,7,8,9}; int brr[] = {1,3,4,6,8,9}; int sb = getInvertNumber(brr,sizeof(brr)/sizeof(brr[0])); cout<<sb<<endl; } int getInvertNumber(int arr[],int nLength) { int nLeft = 0; int nRight = nLength-1; int nMid; if(arr[nLeft]<arr[nRight]) return 0; while(nLeft<nRight) { nMid = ( nLeft + nRight ) / 2; if(arr[nMid]>arr[nLeft]) nLeft = nMid; else nRight = nMid; } return nLength -nMid-1; }
原文:http://www.cnblogs.com/yxwkf/p/5084955.html