Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7abb6f7

Browse files
author
Ram swaroop
committed
search in sorted 2D array : optimized a little bit
1 parent 3438b12 commit 7abb6f7

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/me/ramswaroop/arrays/SearchInSorted2DArray.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,20 @@ public class SearchInSorted2DArray {
1616
* both row wise and column wise.
1717
* <p/>
1818
* Time complexity: O(n) where n is size of 2-D array.
19+
* <p/>
20+
* Explanation:
21+
* Linearly searches across rows and columns until the element is found or till the last element. If
22+
* the element is not found in the 1st row or 1st column then we search in 2nd row and 2nd column
23+
* and so on.
1924
*
2025
* @param a
2126
* @param i
2227
* @param j
2328
* @param value
24-
* @return
29+
* @return an array consisting of co-ordinates if {@param value} is found otherwise {@code new int[]{-1, -1}}.
2530
*/
2631
public static int[] search(int[][] a, int i, int j, int value) {
27-
for (int x = 0; x < a.length; x++) {
32+
for (int x = 0; x < a.length && (a[i][x] <= value || a[x][j] <= value); x++) {
2833
if (a[i][x] == value) {
2934
return new int[]{i, x};
3035
} else if (a[x][j] == value) {

0 commit comments

Comments
 (0)