简体   繁体   English

通过偶数递增和奇数递减的数组进行二进制搜索?

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

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}. 它适用于大多数情况,但不适用于{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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM