Need Help with Binary Searching!

2. Given an array storing integers ordered by value, modify the binary searchalgorithm to return the position of the integer with the greatest value less thanK(K is the key to be searched) when K itself does not appear in the array. Return ERROR if the leastvalue in the array is greater than K.

Above is the question :

#include<stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
int arr[5]={1,3,5,7,9};
int key,middle;
int i=0;
int j=4;
int rec;
middle=(i+j)/2;
cout<<"enter the key";
cin>>key;

if(key==arr[middle])
{
cout<<"key has been found";
}

while(i<=j)
{

if(key>arr[middle])
{
i=middle+1;

}


else if (key<arr[middle])
{
j=middle-1;

}
else
{
cout<<"found";
rec=middle-1;

}
}
getch();
return 0;
}


It is not finding the element at all

But if I press the element 5 it would find out and print but for remaining one it doesn't do.

At the end rec=middle-1; i used this logic for the giving out the highest value less than K.
This will cause you to infinite loop..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
while(i<=j)
{
   if(key>arr[middle])
  {
      i=middle+1;
  }
  else if (key<arr[middle])
  {
     j=middle-1;
  }
  else
 {
    cout<<"found";
    rec=middle-1;
  }
}


lets say you enter key: 7
than your code
i = middle(2) + 1 = 3;
every time while loop will check for (i<=j)
i =3 and j=4;
every time i = middle(2) + 1 will happen and it will check every time.. so, this will enter in infinite loop..
i think you need to do something like middle++ and middle--
and break the loop when number found...
Last edited on
Topic archived. No new replies allowed.