I'm confused at exactly where this happens. I've traced this simple code out on paper as well as used the computer but I can't figure out. In my example I created an array of {1, 2, 3, 4, 5} and it came up with this error for numbers 4 and 5. It worked fine for numbers 1, 2, and 3, as well as numbers not in the array. Can anyone help, please?
public static int search(int[] ar, int num)
{
int low=0;
int hi=ar.length-1;
int mid=(low+hi/2);
while(hi>=low || mid<=low || mid>=hi )
{
if(ar[mid]==num)
{
return mid;
}
else if(ar[mid]>num)
{
hi=mid-1;
mid=(low+hi/2);
}
else
{
low=mid+1;
mid=(low+hi/2);
}
}
return -1;
}