Exact code from Competitive Programmers Handbook. It is supposed to find x in array using binary search.
int t[10]={1,5,7,9,15,48,78,89,94,100};
int x=48; // element to be found
int n=10; // size
int k = 0; // initialize to 0th position
for (int b = n/2; b >= 1; b /= 2) {
while (k+b <= n && t[k+b] <= x) k += b;
}
if (t[k] == x) cout<<"found at "<<k;
else cout<<"Not found";
return 0;
[simon@simon-laptop][08:39:47]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh
Compiling m_vaidya-blah.cpp
Executing command:
g++ -std=c++17 m_vaidya-blah.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv
Successful
[simon@simon-laptop][08:39:50]
[~/devel/hackerrank/otherpeoples]>./a.out
m_vaidya-blah.cpp:12:33: runtime error: index 10 out of bounds for type 'int [10]'
m_vaidya-blah.cpp:12:33: runtime error: load of address 0x7fff99dbb8d8 with insufficient space for an object of type 'int'
0x7fff99dbb8d8: note: pointer points here
64 00 00 00 00 f2 46 15 f0 89 ed 2b 40 db 02 d9 89 7f 00 00 00 00 00 00 00 00 00 00 60 02 4e 72
^
(full code I used to test:
#include <iostream>
using namespace std;
int main()
{
int t[10]={1,5,7,9,15,48,78,89,94,100};
int x=48; // element to be found
int n=10; // size
int k = 0; // initialize to 0th position
for (int b = n/2; b >= 1; b /= 2) {
while (k+b <= n && t[k+b] <= x) k += b;
}
if (t[k] == x) cout<<"found at "<<k;
else cout<<"Not found";
return 0;
}
// This is the solution what you asked for. I have solved the error
#include
using namespace std;
int main()
{
int t[10]={1,5,7,9,15,48,78,89,94,100};
int x=48; // element to be found
int n=10; // size
int k = 0; // initialize to 0th position
for (int b = n/2; b >= 1; b /= 2)
{
while (k+b <= n && t[k+b] <= x)
k += b;
}
if (t[k] == x) cout<<"found at "<<k;
else cout<<"Not found";
return 0;