Binary search through an array of even numbers increasing and odd numbers decreasing?

StackOverflow https://stackoverflow.com/questions/22540756

  •  18-06-2023
  •  | 
  •  

سؤال

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;        
}
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top