//题目:在旋转有序数组中查找目标值
//给定一个升序排序的整数数组,该数组可能已经被旋转了。也就是说,数组中的一部分元素被移到了数组的末尾。编写一个算法来在这个旋转有序数组中查找给定的目标值,并返回目标值在数组中的索引。如果目标值不存在于数组中,则返回 - 1。
//
//问题函数定义:
//
//cpp
//int searchInRotatedSortedArray(int arr[], int n, int target);
//裁判测试程序样例:
//cpp
#include <iostream>
int searchInRotatedSortedArray(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
// 判断哪一半是有序的
if (arr[left] <= arr[mid]) {
// 左半部分有序
if (arr[left] <= target && target < arr[mid]) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
else {
// 右半部分有序
if (arr[mid] < target && target <= arr[right]) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
}
return -1;
}
int main() {
int arr[] = { 15, 19, 21, 23, 4, 5, 7, 9, 12 };
int n = sizeof(arr) / sizeof(arr[0]);
int target = 7;
int index = searchInRotatedSortedArray(arr, n, target);
if (index != -1) {
std::cout << "Target " << target << " found at index: " << index << std::endl;
}
else {
std::cout << "Target " << target << " not found in the array." << std::endl;
}
return 0;
}
//输出样例:
//目标值 7 在索引:6