如何修改程序以返回值= 8索引8,即从右开始的第一个索引“ 8”(而不是现在的索引6,即从左开始的第一个索引“ 8”)。对于value = 7,程序正确返回索引5(数组值6)。
#include "pch.h"
#include <iostream>
int arr[10]{0, 2, 3, 5, 5, 6, 8, 8, 8, 9};
int arr_size = sizeof(arr) / sizeof(arr[0]);
int main()
{
for (int i = 0; i <= arr_size; i++)
{
printf("%i\n", arr[i]);
}
printf("\n");
int left = 0;
int right = arr_size - 1;
int middle = 0;
int value = 8 ;
int x = 0;
int index = 0;
//* Searching for value in ascending sorted array
while (left <= right) {
middle = (left + right) / 2;
if (arr[middle] <= value) {
x = arr[middle];
index = middle;
}
if (value > arr[middle]) {
left = middle + 1;
}
else {
right = middle - 1;
}
}
printf("Found %i at position %i\n", x, index);
}
答案 0 :(得分:1)
只需使用std::upper_bound()
:
int arr[] = {0, 2, 3, 5, 5, 6, 8, 8, 8, 9};
auto beg = std::begin(arr);
auto it = std::upper_bound( beg, std::end(arr), 8 );
if( it == beg ) {
std::cout << "no value less than 8 found" << std::endl;
return 0;
}
std::cout << "index is " << std::distance( beg, it ) - 1 << std::endl;