Question #282011

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.


Expert's answer

#include <iostream>


int index(int* arr, const int size, int value)
{
    for (int i = 0; i != size; ++i)
    {
        if (arr[i] == value)
        {
            return i;
        }
        else if (arr[i] < value && value < arr[i + 1])
        {
            return i + 1;
        }
    }
}


int main()
{
    int arr[5] = { 1, 3, 5, 9, 11 };
    std::cout << index(arr, 5, 4);
    


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS