Reputation: 679
I know my code is a mess and I'm sorry for that, I tried to write it as fast as possible and than to arrange the statements.
it works for most cases but not for {19,17,2,15,6,13,12,7,16,3,22}.
as you can see it should be simple, the array can be sorted in any way, but the even numbers always increase from the beginning to the end, and the odd numbers decrease.
what I tried to do was a regular binary search with some conditions to check if we look at an even or odd number and than adjust accordingly.
Edit: I forgot to mention it's a question I'm trying to solve, they said specifically search the array in the most efficient way.
public static int find(int[] arr,int n)
{
final boolean EVEN;
if (n%2==0)
EVEN = true;
else
EVEN = false;
int min = 0, max = arr.length-1;
int m = 0;
do
{
m = (min+max)/2;
if (n == arr[m])
break;
if (arr[m]%2==0)
{
if (EVEN)
{
if (n>arr[m])
min = m+1;
else
max = m-1;
}
else
{
do
{
m--;
}
while(arr[m]%2==0);
if (arr[m]==n)
break;
if (n>arr[m])
max = m-1;
else
min = m+1;
}
}
else
{
if (!EVEN)
{
if (n>arr[m])
max = m-1;
else
min = m+1;
}
else
{
do
{
m++;
}
while(arr[m]%2!=0);
if (arr[m]==n)
break;
if (n>arr[m])
min = m+1;
else
max = m-1;
}
}
}while(min<max);
if (arr[m]==n)
return m;
else
return -1;
}
Upvotes: 0
Views: 7084
Reputation: 904
Try
while(min<=max);
You might be missing the cases where min and max coincide.
Update:
Yup! I checked it. I ran your program against
int[] array = {19,17,2,15,6,13,12,7,16,3,22};
for all values and it works as expected if you make that correction.
Upvotes: 2