60 578
Assignments Done
97,9%
Successfully Done
In April 2018

Answer to Question #60931 in C# for Eryc Shawn

Question #60931
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.
Computer Science 65
ii. Name the header file to which the following built in functions belong to :-
a) cos() b) strcpy()
ii. Difference between:-
a) Global and local variable
b) Call by value and Call by reference
Expert's answer
#include <iostream>

using namespace std;

int binarySearch(int, int*, int);

int main()
{
int *array;
int size;
int value;
cout << "Enter size of array: ";
cin >> size;
array = new int[size];
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
cout << "Enter value for search: ";
cin >> value;
int index = binarySearch(size, array, value);
if (index >= 0)
cout << "Element is found, its location " << index << endl;
else
cout << "Element not found" << endl;
return 0;
}

int binarySearch(int size, int* array, int value) {
int first = 0;
int last = size;
while (last > first)
{
int mid = (last + first) / 2;
if (array[mid] == value)
return mid;
if (value > array[mid])
first = mid + 1;
else
last = mid - 1;
}
return -1;
}

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 first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions