二维数组中的查找

来源:互联网 发布:图文并茂用什么软件 编辑:程序博客网 时间:2024/06/05 10:50
package com.a.b;public class MatrixSearch {private static int[][] data = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 },{ 4, 7, 10, 13 }, { 6, 8, 11, 15 } };private static int[] data2 = { 1, 2, 8, 9, 2, 4, 9, 12, 4, 7, 10, 13, 6, 8,11, 15 };public static void main(String[] args) {//注意测试功能、边界、特殊值int n = 5;// System.out.println(search(data, n));// System.out.println(search(data2, 4, 4, n));print(data2, 4, 4);}/** * 二维数组中查找 * @param matrix * @param n * @return */private static boolean search(int[][] matrix, int n) {// O(n^2)for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[i].length; j++) {if (data[i][j] == n) {System.out.println("(" + i + "," + j + ")");return true;}}}return false;}/** * 行、列都升序的数组查找 * @param matrix * @param rows * @param columns * @param n * @return */private static boolean search(int[] matrix, int rows, int columns, int n) {boolean found = false;if (matrix != null && rows > 0 && columns > 0) {int row = 0, column = 3;while (row < rows && column >= 0) {System.out.println("(" + row + "," + column + ")="+ matrix[row * columns + column]);if (matrix[row * columns + column] == n) {found = true;break;} else if (n < matrix[row * columns + column]) {--column;} else {++row;}}}return found;}/** * 以二维数组的形式读取一维数组 *  * @param matrix * @param rows * @param columns */private static void print(int[] matrix, int rows, int columns) {if (matrix != null && rows > 0 && columns > 0) {int row = 0, column = 0;while (row < rows && column < columns) {System.out.println("(" + row + "," + column + ")="+ matrix[row * columns + column]);if (++column >= columns) {column %= columns;++row;}}}}}

0 0