Skip to content

Instantly share code, notes, and snippets.

@pablocortez
Created May 13, 2017 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablocortez/83fd7c7e55f6bde36dfa2973d375c2fd to your computer and use it in GitHub Desktop.
Save pablocortez/83fd7c7e55f6bde36dfa2973d375c2fd to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
int main()
{
int number_to_find = 7;
int array[] = { 1, 3, 4, 6, 7, 8, 10, 13, 14, 18, 19, 21, 24, 37, 40, 45, 71 };
int min = 0;
int max = (sizeof(array) / sizeof(*array) - 1); // last index value
int guess;
while (min <= max)
{
guess = (int)(((max + min) / 2) + 0.5);
if (number_to_find == array[guess])
{
cout << "The number is at index " << guess << endl;
break;
} else if (array[guess] < number_to_find) {
min = guess + 1;
} else {
max = guess - 1;
}
cout << guess << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment