mid+1] > arr[mid])) //递增部分
low = mid;
else
high = mid;
}
}
//递增部分的二分查找
int BinSearchLeft(int arr[], int begin, int end, int target)
{
int low = begin;
int high = end - 1;
int mid = 0;
while (low <= high)
{
mid = (low + high) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
//递减部分的二分查找
int BinSearchRight(int arr[], int begin, int end, int target)
{
int low = begin;
int high = end - 1;
int mid = 0;
while (low <= high)
{
mid = (low + high) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] > target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
//算法思想:先找到最大元素的索引,然后对左右两个部分进行二分查找
int FindTargetIndex(int arr[], int n, int target)
{
int maxIndex = FindMax(arr, n);
if (arr[maxIndex] == target)
return maxIndex;
int res = 0;
if ((res = BinSearchLeft(arr, 0, maxIndex, target)) != -1)
return res;
if ((res = BinSearchRight(arr, maxIndex + 1, n, target)) != -1)
return res;
return -1;
}
int main()
{
int arr[] = {2, 3, 4, 5, 10, 7, 6, 1};
int size = sizeof(arr) / sizeof(int);
int maxIndex = FindMax(arr, size);
if (-1 != maxIndex)
cout<<"the max element's index is "<
int res = FindTargetIndex(arr, size, 3);
if (-1 != res)
cout<<"the target's position is "< else
cout<<"can not find this target!"<
return 0;
}
作者“wangyangkobe的专栏”