繁体   English   中英

递归鞍背 - 在 Java 中的已排序二维数组中搜索元素

[英]Recursive saddleback - searching for an element in sorted 2D array in Java

我在 Java 的排序二维数组中编码鞍背搜索,奇怪的事情发生了。

算法必须在数组中找到给定k元素的第一次出现(首先是行,然后是列)。 然后它还应该显示在哪个索引上找到了给定的数字。

我迭代地编写了鞍背算法并且它可以工作,但是在将其重新编码为递归之后 - 它没有。

对于数组

10 10 10 10 10 20 20 30 20 20 20 40

k: 20

它输出,在给定的数组中找不到 k。

此外 - 该算法的复杂度必须低于 O(n,m)^3,因此任何其他算法技巧都会受到赞赏。

这是我的代码:

static boolean RekPier(int tab[][], int i, int j, int m, int n, int k){

        System.out.println(i + " " + j + " " + tab[i][j]);

        if (tab[i][j] == k && i < m && j < n){
            findex = i;
            lindex = j;
            return true;
        }

        else if((tab[i][j] > k || tab[i][n-1] < k) && (i < m && j < n)){

            int i1 = i+1;

            if(i1 == m) return false;

            RekPier(tab, i1, 0, m, n, k);
        }

        else if (i < m && j < n){

            int j1 = j+1;

            if(j1 == n) return false;

            RekPier(tab, i, j1, m, n, k);
        }

        return false;
    }

您的实现有一些错误,但我修改了 function,如下所示:

static int RekPier(int arr[][], int i, int j,int M ,int N,int Value)
{
    // If the entire column is traversed
    if (j >= M)
        return 0;

    // If the entire row is traversed
    if (i >= N)
        return 1;

    if(arr[i][j] == Value){
        System.out.println("Row:" +i +'\t' +"Column:" +j);
    }

    // Recursive call to traverse the matrix in the Horizontal direction
    if (RekPier(arr, i,j + 1, M, N,Value) == 1)
        return 1;

    // Recursive call for changing the Row of the matrix
    return RekPier(arr,i + 1,0, M, N,Value);
}

和你一样复杂

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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