package org.wesome.dsalgo;
public class SortedMatrixSearch {
public static int[] sortedMatrixSearch(int[][] matrix, int dimension, int find) {
int[] pos;
int row = 0, col = dimension - 1;
while (row < dimension && col >= 0) {
if (matrix[row][col] == find) {
System.out.println(find + " is present at [" + row + "][" + col + "]");
pos = new int[]{row, col};
return pos;
}
if (matrix[row][col] > find) {
System.out.println(find + " is less then last element " + matrix[row][col] + " at [" + row + "][" + col + "], hence decrementing colum");
col--;
} else {
System.out.println(find + " is greater then last element " + matrix[row][col] + " at [" + row + "][" + col + "], hence incrementing row");
row++;
}
}
System.out.println(find + " is not present");
pos = new int[]{-1, -1};
return pos;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.wesome.dsalgo.SortedMatrixSearch.sortedMatrixSearch;
public class SortedMatrixSearchTest {
@Test
void sortedMatrixSearchTest1() {
int dimension = 4;
int[][] arr = {{0, 6, 8, 9},
{20, 22, 28, 29},
{36, 38, 50, 61},
{64, 66, 100, 122}};
int find = 0;
int[] pos = new int[]{0, 0};
Assertions.assertArrayEquals(pos, sortedMatrixSearch(arr, dimension, find));
}
@Test
void sortedMatrixSearchTest2() {
int dimension = 4;
int[][] arr = {{0, 6, 8, 9},
{20, 22, 28, 29},
{36, 38, 50, 61},
{64, 66, 100, 122}};
int find = 20;
int[] pos = new int[]{1, 0};
Assertions.assertArrayEquals(pos, sortedMatrixSearch(arr, dimension, find));
}
@Test
void sortedMatrixSearchTest3() {
int dimension = 4;
int[][] arr = {{0, 6, 8, 9},
{20, 22, 28, 29},
{36, 38, 50, 61},
{64, 66, 100, 122}};
int find = 122;
int[] pos = new int[]{3, 3};
Assertions.assertArrayEquals(pos, sortedMatrixSearch(arr, dimension, find));
}
@Test
void sortedMatrixSearchTest4() {
int dimension = 4;
int[][] arr = {{0, 6, 8, 9},
{20, 22, 28, 29},
{36, 38, 50, 61},
{64, 66, 100, 122}};
int find = 61;
int[] pos = new int[]{2, 3};
Assertions.assertArrayEquals(pos, sortedMatrixSearch(arr, dimension, find));
}
@Test
void sortedMatrixSearchTest5() {
int dimension = 4;
int[][] arr = {{0, 6, 8, 9},
{20, 22, 28, 29},
{36, 38, 50, 61},
{64, 66, 100, 122}};
int find = 38;
int[] pos = new int[]{2, 1};
Assertions.assertArrayEquals(pos, sortedMatrixSearch(arr, dimension, find));
}
@Test
void sortedMatrixSearchTest6() {
int dimension = 4;
int[][] arr = {{0, 6, 8, 9},
{20, 22, 28, 29},
{36, 38, 50, 61},
{64, 66, 100, 122}};
int find = 37;
int[] pos = new int[]{-1, -1};
Assertions.assertArrayEquals(pos, sortedMatrixSearch(arr, dimension, find));
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.2.0"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}