Answer to Question #84716 in C++ for Shivam

Question #84716
Write a program in c++ to read an array of sorted integers.Search for a value using binary search method.If the element is found,print its location else print element not found.
1
Expert's answer
2019-02-01T05:36:03-0500

#include <iostream>


#define lm(m) sizeof(m)/sizeof(*m)


using namespace std;


int main()

{

int a[11] = { -89, -2, 5, 10, 32, 556, 895, 1000, 1001, 1032, 98453 };

int left = -1;

int right = lm(a);

int mid, key = 895;

while (left < right - 1)

{

mid = (left + right) / 2;

if (a[mid] < key)

{

left = mid;

}

else

{

right = mid;

}

}

if (a[right] == key)

{

cout << "The index of " << key << " is " << right << endl;

}

else

{

cout << "No " << key << " found.\n";

}

system("pause");

}

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
APPROVED BY CLIENTS