排序矩阵搜索

时间:2016-03-24 16:28:42

标签: java arrays search matrix netbeans

我在for循环之后直接在行上接收一个ArrayIndexOutOfBounds。我还想知道如何继续循环矩阵来迭代行或列,直到达到目标。

在给定的矩阵中,我想从左下角开始。如果目标值小于所选数字,则该行向上移动。如果目标值大于所选数字,则列向右移动一个。

 public static void optimizedSearch(int matrix[][], int array_size, int target) {
    int row = 0;
    int col = array_size-1;
    boolean found = false;
    int comparison_counter = 0;
    int end = array_size * 2;

    //while (!found) {
    for (int i = 0; i < 100 && !found; i++) {
        if (matrix[row][col] < target ) {
            row++;
            comparison_counter++;
        } else if (matrix[row][col] > target) {
            col--;
            comparison_counter++;
        } else if (matrix[row][col] == target) {
            found = true;
        } else if ((i == end) && (found == false)) {
            found=false;
        }
    }// end for loop

    if (found == true) {
        System.out.println(target + " found in " + comparison_counter + " number of comparisons using optimized search");

    } else 
        System.out.println(target + " not found in " + comparison_counter + " number of comparisons using optimized search");

} //end optimizedSearch

0 个答案:

没有答案