Ask coding questions

← Back to all posts
What I have bad in this code?
GrabielPerez (0)

#include<iostream>

using namespace std;

int binarySearch(int array[], int size, int searchValue)

{
float num = 0.0f;

int low = 0;
int high = size - 1;

int mid;

while (low <= high)
{
	int mid = (low + high) / 2;

	if (searchValue == array[mid])
	{
		return mid;
	}
	else if (searchValue > array[mid])
	{
		low = mid + 1;
	}
	else
	{
		high = mid - 1;
	}
}

return -1;

}

int main()
{
int array[] = { 1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95 };

int n = sizeof(array) / sizeof(array[0]);
cout << "Enter an integer";
int searchValue;
cin >> searchValue;
int index = binarySearch(array, n - 1, searchValue);
if (index == -1)
	cout << searchValue << "is not present in the array" << endl;
else
	cout << searchValue << " is present at index " << index << " in the array" << endl << endl;

{

	char inputChar = 'x';
	cout << " Enter search key to continue, or press X to exit" << endl;
	cin >> inputChar;
	if (inputChar == 'x' || inputChar == 'X')
	{
		cout << "Exiting..." << endl;
	}
	else
		cout << "Continuing..." << endl;
	return main();
	{
	}
}

}

Answered by DynamicSquid (5023) [earned 5 cycles]
View Answer
Comments
hotnewtop
DynamicSquid (5023)

Could you link the repl?

DynamicSquid (5023)

@GrabielPerez Line 46, it should be :

int index = binarySearch(array, n, searchValue);

Also everything else in your code is working fine

GrabielPerez (0)

@DynamicSquid Thank you so much for the help!

InvisibleOne (3208)

What error are you getting?

GrabielPerez (0)

@InvisibleOne when I put the last number of the row it tells me that that number is not present in the row and with the rest of the numbers it tells me that they are in a smaller place than where it really is.