【问题标题】:Problems using Binary Search使用二分搜索的问题
【发布时间】:2014-05-09 20:50:30
【问题描述】:

我目前正在编写一些代码来解决作业中的数独难题。我目前编写的代码应该是隔离我们需要插入值的行和列,然后测试值 1-9 以查看哪些已经出现在行或列中。问题是,二进制搜索没有检测到一些数字,我不知道为什么。这是我的代码。你需要做的只是 A.grid 是一个包含未解决难题的数组,而设置值方法是我编写的一种方法,用于使用 fromat setValue(xLocation, yLocation, value) 将值插入到数组中

int currentVal = 0;
    int j;
    int [] currentRow = new int [9];
    int [] currentCol = new int [9];
    for (i = 0; i<9 ; i++) {
        for (j = 0; j<9 ; j++){
            currentVal=A.grid[i][j];
            boolean keepGoing = true;
            int newVal=1;
            if (currentVal==0) {
                for( int k = 0; k < 9; k++) 
                {currentCol[k] = A.grid[k][j];
                        }
                    currentRow = A.grid[i];
                    log(Arrays.toString(currentRow));
                    log(Arrays.toString(currentCol));
                    log("");
                while (keepGoing) {
                        int indexRow=Arrays.binarySearch(currentRow, newVal);
                        int indexCol=Arrays.binarySearch(currentCol, newVal);
                        log(indexRow);
                        log(indexCol);
                        log("");
                        if (indexRow<0 && indexCol<0) {
                            keepGoing = false;
                        }
                        newVal++;

            }
            A.setValue(j, i, newVal-1); 

谢谢!

【问题讨论】:

    标签: java search binary


    【解决方案1】:

    我不确定这是否是您唯一的问题,但如果您要使用二进制搜索算法,则需要确保您的数组已排序。否则,您将得到垃圾结果。

    话虽如此,你为什么认为你需要对只有 9 个元素的数组进行二进制搜索?自己手动进行搜索而完全忘记使用二分搜索很可能会更快。

    int indexRow = -1;
    for (int z = 0; z < 9; ++z)
    {
        if (currentRow[z] == newVal)
        {
            indexRow = z;
            break;
        }
    }
    
    // indexRow is now the index of newVal in currentRow
    

    就此而言,如果将整个例程封装在一个单独的函数中可能会更清楚:

    int search(int[] source, int val)
    {
        for (int z = 0; z < source.length; ++z)
        {
            if (source[z] == val)
            {
                // z is the position of val in the source array
                return z;
            }
        }
    
        // Return -1 if val is not present
        return -1;
    }
    

    然后,您可以将 binarySearch() 调用替换为对 search() 的调用。

    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多