Answer to Question #282011 in C++ for devi

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.


1
Expert's answer
2021-12-22T14:18:44-0500
#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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog