在无限排序数组中找到一个元素

时间:2012-09-21 17:24:28

标签: arrays algorithm

我把这作为面试问题......

无限数组,它是从某个位置排序的(我们不知道位置)只有特殊符号'$',我们需要在那个数组中找到一个元素......

我给出了一个解决方案,比如获得$的第一次出现,然后在$

的前一部分进行二元搜索

找到第一次出现$ i给出了像窗口大小增量的解决方案if(i,2i)

我给的代码是

#include<stdio.h>

int first(int *arr,int start,int end,int index)
{
    int mid=(start+end)/2;
    if((mid==start||arr[mid-1] != '$') && arr[mid]=='$')
        return mid;
    if(arr[mid]=='$')
        return first(arr,start,mid-1,index);
    else
    {
        if(arr[end] =='$')
            return first(arr,mid+1,end,index);
        else
            return first(arr,end+1,(1<<index),index+1);
    }
}

int binsearch(int *arr,int end ,int n)
{
    int low,high,mid;
    high=end-1;
    low=0;
    while(low<= high)
    {
        mid=(low+high)/2;
        if(n<arr[mid])
            high=mid-1;
        else if (n >arr[mid])
            low=mid+1;
        else
            return mid;
    }
    return -1;
}

int main()
{
    int arr[20]={1,2,3,4,5,6,7,8,9,10,'$','$','$','$','$','$','$','$','$','$'};
    int i =first(arr,0,2,2);
    printf("first occurance of $ is  %d\n",i);
    int n=20;//n is required element to be found
    if(i==0||arr[i-1]<n)
        printf(" element %d not  found",n);
    else{
        int p=binsearch(arr,i,n);
        if(p  != -1)
            printf("element %d is found at index %d",n,p);
        else
            printf(" element %d not found",n);
    }
    return 0;
}

有没有更好的方法来解决上述问题?

而且我也想知道找到第一次出现$为什么我们应该仅以2的幂移动窗口为什么不是3(i,3i)

有人可以通过关于复发关系的一些解释来帮助......

3 个答案:

答案 0 :(得分:3)

似乎是对我这样做的好方法。作为一项小规模优化,当您的任何数字大于您要搜索的数字时,您可以停止first例程(不只是$)。

以2的幂增长窗口意味着您将在log_2(n)次迭代中找到结束。因子3的增长意味着你会在log_3(n)迭代中找到它,这个迭代更小。但不是渐近变小,如O(log_2(n)) == O(log_3(n))。无论如何,您的二进制搜索将采取log_2(n)步骤,因此更快地使first部分无法帮助您的大O运行时间。

答案 1 :(得分:0)

迭代格式的第一个函数的有效部分是

private int searchNum(int[] arr, int num, int start, int end) {
    int index = 0;
    boolean found = false;
    for (int i = 0; i < arr.length; i = 1 << index) {
        if (start + i < arr.length) {
            if (arr[start] <= num && arr[start + i] >= num) {
                found = true;
                return bsearch(arr, num, start, start + i);
            } else {
                start = start + i;
            }
        } else {
            return bsearch(arr, num, start, arr.length - 1);
        }
    }
    return 0;
}

这不会让你第一次出现,而是试图直接找到数字,因为在你的情况下,你错过了在找到$符号之前找到数字本身的可能性。所以最坏的情况复杂性是O(logn).. 最好的情况是(1) 之后你将其传递给

private int bsearch(int[] array, int search, int first, int last) {
    int middle = (first + last) / 2;
    while (first <= last) {
        if (array[middle] < search)
            first = middle + 1;
        else if (array[middle] == search) {
            System.out.println(search + " found at location "
                    + (middle + 1) + ".");
            return middle;
        } else
            last = middle - 1;

        middle = (first + last) / 2;
    }
    if (first > last)
        System.out.println(search + " is not present in the list.\n");
    return -1;
}

调用函数

    if ((pos = searchNum(arr, num, 0, 2)) != -1) {
        System.out.println("found @ " + pos);
    } else {
        System.out.println("not found");
    }

答案 2 :(得分:0)

这是python解决方案。

arr = [3,5,7,9,10,90,100,130,140,160,170,171,172,173,174,175,176]
elm = 171
k = 0
while (True):
    try:
        i = (1 << k) - 1 #  same as 2**k - 1 # eg 0,1,3,7,15
        # print k
        if(arr[i] == elm):
            print "found at " + str(i)
            exit()
        elif( arr[i] > elm):
            break                   

    except Exception as e:          
        break
    k = k+1

begin = 2**(k-1) # go back to previous power of 2
end = 2**k -1 

# Binary search
while (begin <= end):
    mid = begin + (end-begin)/2
    try:
        if(arr[mid] == elm):
            print "found at " + str(mid)
            exit()          
        elif(arr[mid] > elm):
            end = mid-1
        else:
            begin = mid+1

    except Exception as e:
        # Exception can occur if you are trying to access min element and that is not available. hence set end to mid-1
        end = mid-1


print "Element not found"