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

标签 java arrays algorithm sorting

我正在用 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;
    }

最佳答案

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

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);
}

与您的复杂程度相同

关于java - 递归鞍背 - 在 Java 中搜索已排序的二维数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61444792/

相关文章:

java - Nashorn - 找不到 ScriptObject 和 MyInterface 的通用类加载器

java - Jtable中的AutorowSorter链接到mysql

arrays - 使用 Ruby 生成多重集的分区

python - 循环遍历一组 Python 数字或一组字母是否更快?

java - 使用哪种设计模式?

java - 元素不可点击

python - 获取掩码数组的最小值

php - 将json数组插入mysql数据库

algorithm - Algorithm在建模语言中的对应是什么?

algorithm - 什么时候使用 Paxos(真正的实际用例)?