Given a sorted matrix mat[n][m] and an element ‘x’. Find the position of x in the matrix if it is present, else print -1. Matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, where 1 <= i <= n-1, the first element of row ‘i’ is greater than or equal to the last element of row ‘i-1’. The approach should have O(log n + log m) time complexity.
Examples:
Input : mat[][] = { {1, 5, 9},
{14, 20, 21},
{30, 34, 43} }
x = 14
Output : Found at (1, 0)
Input : mat[][] = { {1, 5, 9, 11},
{14, 20, 21, 26},
{30, 34, 43, 50} }
x = 42
Output : -1
The Brute Force and Easy Way To do it:
The Approach: the approach is very simple that we use to have linear search/mapping thing.
C++
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
int n = 4;
int m = 5;
int a[n][m] = {{0, 6, 8, 9, 11},
{20, 22, 28, 29, 31},
{36, 38, 50, 61, 63},
{64, 66, 100, 122, 128}};
int k = 31;
map< int ,pair< int , int >>mp;
for ( int i=0;i<n;i++){
for ( int j=0;j<m;j++){
if (k==a[i][j]){
cout<< "Found at (" <<i<< "," <<j<< ")" <<endl;
}
mp[a[i][j]]={i,j};
}
}
if (mp.find(k)!=mp.end()){
cout<< "This is how we can found using mapping: " <<endl;
cout<< "(" <<mp[k].first<< "," <<mp[k].second<< ")" <<endl;
} else {
cout<< "Not Found" <<endl;
}
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) {
int n = 4 ;
int m = 5 ;
int [][] a = { { 0 , 6 , 8 , 9 , 11 },
{ 20 , 22 , 28 , 29 , 31 },
{ 36 , 38 , 50 , 61 , 63 },
{ 64 , 66 , 100 , 122 , 128 } };
int k = 31 ;
Map<Integer, int []> mp = new HashMap<>();
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < m; j++) {
if (k == a[i][j]) {
System.out.println( "Found at (" + i + "," + j + ")" );
}
mp.put(a[i][j], new int [] { i, j });
}
}
if (mp.containsKey(k)) {
System.out.println( "This is how we can found using mapping: " );
int [] indexes = mp.get(k);
System.out.println( "(" + indexes[ 0 ] + "," + indexes[ 1 ] + ")" );
} else {
System.out.println( "Not Found" );
}
}
}
|
Python3
n = 4
m = 5
a = [[ 0 , 6 , 8 , 9 , 11 ],
[ 20 , 22 , 28 , 29 , 31 ],
[ 36 , 38 , 50 , 61 , 63 ],
[ 64 , 66 , 100 , 122 , 128 ]]
k = 31
mp = {}
for i in range (n):
for j in range (m):
if (k = = a[i][j]):
print ( "Found at (" , i, "," , j, ")" )
mp[a[i][j]] = [i, j]
if k in mp:
print ( "This is how we can found using mapping: " )
print ( "(" , mp[k][ 0 ], "," , mp[k][ 1 ], ")" )
else :
print ( "Not Found" )
|
C#
using System;
using System.Collections.Generic;
class MainClass {
public static void Main( string [] args)
{
int n = 4;
int m = 5;
int [, ] a = { { 0, 6, 8, 9, 11 },
{ 20, 22, 28, 29, 31 },
{ 36, 38, 50, 61, 63 },
{ 64, 66, 100, 122, 128 } };
int k = 31;
Dictionary< int , Tuple< int , int > > mp
= new Dictionary< int , Tuple< int , int > >();
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
if (k == a[i, j]) {
Console.WriteLine( "Found at ({0},{1})" ,
i, j);
}
mp[a[i, j]] = Tuple.Create(i, j);
}
}
if (mp.ContainsKey(k)) {
Console.WriteLine(
"This is how we can found using mapping: " );
Console.WriteLine( "({0},{1})" , mp[k].Item1,
mp[k].Item2);
}
else {
Console.WriteLine( "Not Found" );
}
}
}
|
Javascript
let n = 4;
let m = 5;
let a = [[0, 6, 8, 9, 11],
[20, 22, 28, 29, 31],
[36, 38, 50, 61, 63],
[64, 66, 100, 122, 128]];
let k = 31;
let mp = new Map();
for (let i=0;i<n;i++){
for (let j=0;j<m;j++){
if (k==a[i][j]){
console.log(`Found at (${i},${j})`);
}
mp.set(a[i][j], [i,j]);
}
}
if (mp.has(k)){
console.log( "This is how we can found using mapping: " );
console.log(`(${mp.get(k)[0]},${mp.get(k)[1]})`);
} else {
console.log( "Not Found" );
}
|
Output
Found at (1,4)
This is how we can found using mapping:
(1,4)
Time complexity: O(n+m), For traversing.
Auxiliary Space: O(n+m), For mapping.
Please note that this problem is different from Search in a row-wise and column-wise sorted matrix. Here matrix is more strictly sorted as the first element of a row is greater than the last element of the previous row.
A Simple Solution is to one by one compare x with every element of the matrix. If matches, then return the position. If we reach the end, return -1. The time complexity of this solution is O(n x m).
An efficient solution is to typecast a given 2D array to a 1D array, then apply binary search on the typecasted array but will require extra space to store this array.
Another efficient approach that doesn’t require typecasting is explained below.
1) Perform binary search on the middle column
till only two elements are left or till the
middle element of some row in the search is
the required element 'x'. This search is done
to skip the rows that are not required
2) The two left elements must be adjacent. Consider
the rows of two elements and do following
a) check whether the element 'x' equals to the
middle element of any one of the 2 rows
b) otherwise according to the value of the
element 'x' check whether it is present in
the 1st half of 1st row, 2nd half of 1st row,
1st half of 2nd row or 2nd half of 2nd row.
Note: This approach works for the matrix n x m
where 2 <= n. The algorithm can be modified
for matrix 1 x m, we just need to check whether
2nd row exists or not
Example:
Consider: | 1 2 3 4|
x = 3, mat = | 5 6 7 8| Middle column:
| 9 10 11 12| = {2, 6, 10, 14}
|13 14 15 16| perform binary search on them
since, x < 6, discard the
last 2 rows as 'a' will
not lie in them(sorted matrix)
Now, only two rows are left
| 1 2 3 4|
x = 3, mat = | 5 6 7 8| Check whether element is present
on the middle elements of these
rows = {2, 6}
x != 2 or 6
If not, consider the four sub-parts
1st half of 1st row = {1}, 2nd half of 1st row = {3, 4}
1st half of 2nd row = {5}, 2nd half of 2nd row = {7, 8}
According the value of 'x' it will be searched in the
2nd half of 1st row = {3, 4} and found at (i, j): (0, 2)
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
void binarySearch( int mat[][MAX], int i, int j_low,
int j_high, int x)
{
while (j_low <= j_high)
{
int j_mid = (j_low + j_high) / 2;
if (mat[i][j_mid] == x)
{
cout << "Found at (" << i << ", "
<< j_mid << ")" ;
return ;
}
else if (mat[i][j_mid] > x)
j_high = j_mid - 1;
else
j_low = j_mid + 1;
}
cout << "Element no found" ;
}
void sortedMatrixSearch( int mat[][MAX], int n,
int m, int x)
{
if (n == 1)
{
binarySearch(mat, 0, 0, m-1, x);
return ;
}
int i_low = 0;
int i_high = n-1;
int j_mid = m/2;
while ((i_low+1) < i_high)
{
int i_mid = (i_low + i_high) / 2;
if (mat[i_mid][j_mid] == x)
{
cout << "Found at (" << i_mid << ", "
<< j_mid << ")" ;
return ;
}
else if (mat[i_mid][j_mid] > x)
i_high = i_mid;
else
i_low = i_mid;
}
if (mat[i_low][j_mid] == x)
cout << "Found at (" << i_low << ","
<< j_mid << ")" ;
else if (mat[i_low+1][j_mid] == x)
cout << "Found at (" << (i_low+1)
<< ", " << j_mid << ")" ;
else if (x <= mat[i_low][j_mid-1])
binarySearch(mat, i_low, 0, j_mid-1, x);
else if (x >= mat[i_low][j_mid+1] &&
x <= mat[i_low][m-1])
binarySearch(mat, i_low, j_mid+1, m-1, x);
else if (x <= mat[i_low+1][j_mid-1])
binarySearch(mat, i_low+1, 0, j_mid-1, x);
else
binarySearch(mat, i_low+1, j_mid+1, m-1, x);
}
int main()
{
int n = 4, m = 5, x = 8;
int mat[][MAX] = {{0, 6, 8, 9, 11},
{20, 22, 28, 29, 31},
{36, 38, 50, 61, 63},
{64, 66, 100, 122, 128}};
sortedMatrixSearch(mat, n, m, x);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int MAX = 100 ;
static void binarySearch( int mat[][], int i, int j_low,
int j_high, int x)
{
while (j_low <= j_high)
{
int j_mid = (j_low + j_high) / 2 ;
if (mat[i][j_mid] == x)
{
System.out.println ( "Found at (" + i
+ ", " + j_mid + ")" );
return ;
}
else if (mat[i][j_mid] > x)
j_high = j_mid - 1 ;
else
j_low = j_mid + 1 ;
}
System.out.println ( "Element no found" );
}
static void sortedMatrixSearch( int mat[][], int n,
int m, int x)
{
if (n == 1 )
{
binarySearch(mat, 0 , 0 , m - 1 , x);
return ;
}
int i_low = 0 ;
int i_high = n - 1 ;
int j_mid = m / 2 ;
while ((i_low + 1 ) < i_high)
{
int i_mid = (i_low + i_high) / 2 ;
if (mat[i_mid][j_mid] == x)
{
System.out.println ( "Found at (" + i_mid + ", "
+ j_mid + ")" );
return ;
}
else if (mat[i_mid][j_mid] > x)
i_high = i_mid;
else
i_low = i_mid;
}
if (mat[i_low][j_mid] == x)
System.out.println ( "Found at (" + i_low + ","
+ j_mid + ")" );
else if (mat[i_low + 1 ][j_mid] == x)
System.out.println ( "Found at (" + (i_low + 1 )
+ ", " + j_mid + ")" );
else if (x <= mat[i_low][j_mid - 1 ])
binarySearch(mat, i_low, 0 , j_mid - 1 , x);
else if (x >= mat[i_low][j_mid + 1 ] &&
x <= mat[i_low][m - 1 ])
binarySearch(mat, i_low, j_mid + 1 , m - 1 , x);
else if (x <= mat[i_low + 1 ][j_mid - 1 ])
binarySearch(mat, i_low + 1 , 0 , j_mid - 1 , x);
else
binarySearch(mat, i_low + 1 , j_mid + 1 , m - 1 , x);
}
public static void main (String[] args)
{
int n = 4 , m = 5 , x = 8 ;
int mat[][] = {{ 0 , 6 , 8 , 9 , 11 },
{ 20 , 22 , 28 , 29 , 31 },
{ 36 , 38 , 50 , 61 , 63 },
{ 64 , 66 , 100 , 122 , 128 }};
sortedMatrixSearch(mat, n, m, x);
}
}
|
Python3
MAX = 100
def binarySearch(mat, i, j_low,
j_high, x):
while (j_low < = j_high):
j_mid = (j_low + j_high) / / 2
if (mat[i][j_mid] = = x):
print ( "Found at (" , i, "," , j_mid, ")" )
return
elif (mat[i][j_mid] > x):
j_high = j_mid - 1
else :
j_low = j_mid + 1
print ( "Element no found" )
def sortedMatrixSearch(mat, n, m, x):
if (n = = 1 ):
binarySearch(mat, 0 , 0 , m - 1 , x)
return
i_low = 0
i_high = n - 1
j_mid = m / / 2
while ((i_low + 1 ) < i_high):
i_mid = (i_low + i_high) / / 2
if (mat[i_mid][j_mid] = = x):
print ( "Found at (" , i_mid, "," , j_mid, ")" )
return
elif (mat[i_mid][j_mid] > x):
i_high = i_mid
else :
i_low = i_mid
if (mat[i_low][j_mid] = = x):
print ( "Found at (" , i_low, "," , j_mid , ")" )
elif (mat[i_low + 1 ][j_mid] = = x):
print ( "Found at (" , (i_low + 1 ), "," , j_mid, ")" )
elif (x < = mat[i_low][j_mid - 1 ]):
binarySearch(mat, i_low, 0 , j_mid - 1 , x)
elif (x > = mat[i_low][j_mid + 1 ] and
x < = mat[i_low][m - 1 ]):
binarySearch(mat, i_low, j_mid + 1 , m - 1 , x)
elif (x < = mat[i_low + 1 ][j_mid - 1 ]):
binarySearch(mat, i_low + 1 , 0 , j_mid - 1 , x)
else :
binarySearch(mat, i_low + 1 , j_mid + 1 , m - 1 , x)
if __name__ = = "__main__" :
n = 4
m = 5
x = 8
mat = [[ 0 , 6 , 8 , 9 , 11 ],
[ 20 , 22 , 28 , 29 , 31 ],
[ 36 , 38 , 50 , 61 , 63 ],
[ 64 , 66 , 100 , 122 , 128 ]]
sortedMatrixSearch(mat, n, m, x)
|
C#
using System;
class GFG
{
static void binarySearch( int [,]mat, int i, int j_low,
int j_high, int x)
{
while (j_low <= j_high)
{
int j_mid = (j_low + j_high) / 2;
if (mat[i,j_mid] == x)
{
Console.Write ( "Found at (" + i +
", " + j_mid + ")" );
return ;
}
else if (mat[i,j_mid] > x)
j_high = j_mid - 1;
else
j_low = j_mid + 1;
}
Console.Write ( "Element no found" );
}
static void sortedMatrixSearch( int [,]mat, int n,
int m, int x)
{
if (n == 1)
{
binarySearch(mat, 0, 0, m - 1, x);
return ;
}
int i_low = 0;
int i_high = n - 1;
int j_mid = m / 2;
while ((i_low + 1) < i_high)
{
int i_mid = (i_low + i_high) / 2;
if (mat[i_mid,j_mid] == x)
{
Console.Write ( "Found at (" + i_mid +
", " + j_mid + ")" );
return ;
}
else if (mat[i_mid,j_mid] > x)
i_high = i_mid;
else
i_low = i_mid;
}
if (mat[i_low,j_mid] == x)
Console.Write ( "Found at (" + i_low +
"," + j_mid + ")" );
else if (mat[i_low + 1,j_mid] == x)
Console.Write ( "Found at (" + (i_low
+ 1) + ", " + j_mid + ")" );
else if (x <= mat[i_low,j_mid - 1])
binarySearch(mat, i_low, 0, j_mid - 1, x);
else if (x >= mat[i_low,j_mid + 1] &&
x <= mat[i_low,m - 1])
binarySearch(mat, i_low, j_mid + 1, m - 1, x);
else if (x <= mat[i_low + 1,j_mid - 1])
binarySearch(mat, i_low + 1, 0, j_mid - 1, x);
else
binarySearch(mat, i_low + 1, j_mid + 1, m - 1, x);
}
public static void Main (String[] args)
{
int n = 4, m = 5, x = 8;
int [,]mat = {{0, 6, 8, 9, 11},
{20, 22, 28, 29, 31},
{36, 38, 50, 61, 63},
{64, 66, 100, 122, 128}};
sortedMatrixSearch(mat, n, m, x);
}
}
|
Javascript
<script>
let MAX = 100;
function binarySearch(mat, i, j_low, j_high, x)
{
while (j_low <= j_high)
{
let j_mid = Math.floor((j_low + j_high) / 2);
if (mat[i][j_mid] == x)
{
document.write( "Found at (" + i + ", " +
j_mid + ")" );
return ;
}
else if (mat[i][j_mid] > x)
j_high = j_mid - 1;
else
j_low = j_mid + 1;
}
document.write( "Element no found<br>" );
}
function sortedMatrixSearch(mat, n, m, x)
{
if (n == 1)
{
binarySearch(mat, 0, 0, m - 1, x);
return ;
}
let i_low = 0;
let i_high = n - 1;
let j_mid = Math.floor(m / 2);
while ((i_low + 1) < i_high)
{
let i_mid = Math.floor((i_low + i_high) / 2);
if (mat[i_mid][j_mid] == x)
{
document.write( "Found at (" + i_mid +
", " + j_mid + ")" );
return ;
}
else if (mat[i_mid][j_mid] > x)
i_high = i_mid;
else
i_low = i_mid;
}
if (mat[i_low][j_mid] == x)
document.write( "Found at (" + i_low +
"," + j_mid + ")" );
else if (mat[i_low + 1][j_mid] == x)
document.write( "Found at (" + (i_low + 1) +
", " + j_mid + ")" );
else if (x <= mat[i_low][j_mid - 1])
binarySearch(mat, i_low, 0, j_mid - 1, x);
else if (x >= mat[i_low][j_mid + 1] &&
x <= mat[i_low][m - 1])
binarySearch(mat, i_low, j_mid + 1,
m - 1, x);
else if (x <= mat[i_low + 1][j_mid - 1])
binarySearch(mat, i_low + 1, 0,
j_mid - 1, x);
else
binarySearch(mat, i_low + 1, j_mid + 1,
m - 1, x);
}
let n = 4, m = 5, x = 8;
let mat = [ [ 0, 6, 8, 9, 11 ],
[ 20, 22, 28, 29, 31 ],
[ 36, 38, 50, 61, 63 ],
[ 64, 66, 100, 122, 128 ] ];
sortedMatrixSearch(mat, n, m, x);
</script>
|
Time complexity: O(log n + log m). O(Log n) time is required to find the two desired rows. Then O(Log m) time is required for binary search in one of the four parts with a size equal to m/2.
Auxiliary Space: O(1)
This method is contributed by Ayush Jauhari.
Method 2: Using binary search in 2 dimensions
This method also has the same time complexity: O(log(m) + log(n)) and auxiliary space: O(1), but the algorithm is much easier and the code way cleaner to understand.
Approach: We can observe that any number (say k) that we want to find, must exist within a row, including the first and last elements of the row (if it exists at all). So we first find the row in which k must lie using binary search ( O(log N) ) and then use binary search again to search in that row( O(log M) ).
Algorithm:
1) first we’ll find the correct row, where k=2 might exist. To do this we will simultaneously apply binary search on the first and last column.
low=0, high=n-1
i) if( k< first element of row(a[mid][0]) ) => k must exist in the row above
=> high=mid-1;
ii) if( k> last element of row(a[mid][m-1])) => k must exist in the row below
=> low=mid+1;
iii) if( k> first element of row(a[mid][0]) && k< last element of row(a[mid][m-1]))
=> k must exist in this row
=> apply binary search in this row like in a 1-D array
iv) i) if( k== first element of row(a[mid][0]) || k== last element of row(a[mid][m-1])) => found
Example:
let k=2; n=3,m=4;
matrix a: [0, 1, 2, 3 ]
[10,11,12,13]
[20,21,22,23]
1) low=0, high=n-1(=2) => mid=1 //check 1st row [0....3]
-->[10...13]<--
[20...23]
k < a[mid][0] => high = mid-1;(=1)
2) low=0, high=1; =>mid=0; //check 0th row -->[0...3]<--
k>a[mid][0] && k<a[mid][m-1] => k must exist in this row
now simply apply binary search in 1-D array: [0,1,2,3]
Below is the implementation of the above algorithm:
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
void binarySearch( int a[][MAX], int n, int m, int k, int x)
{
int l = 0, r = m - 1, mid;
while (l <= r)
{
mid = (l + r) / 2;
if (a[x][mid] == k)
{
cout << "Found at (" << x << "," << mid << ")" << endl;
return ;
}
if (a[x][mid] > k)
r = mid - 1;
if (a[x][mid] < k)
l = mid + 1;
}
cout << "Element not found" << endl;
}
void findRow( int a[][MAX], int n, int m, int k)
{
int l = 0, r = n - 1, mid;
while (l <= r)
{
mid = (l + r) / 2;
if (k == a[mid][0])
{
cout << "Found at (" << mid << ",0)" << endl;
return ;
}
if (k == a[mid][m - 1])
{
int t = m - 1;
cout << "Found at (" << mid << "," << t << ")" << endl;
return ;
}
if (k > a[mid][0] && k < a[mid][m - 1])
{
binarySearch(a, n, m, k, mid);
return ;
}
if (k < a[mid][0])
r = mid - 1;
if (k > a[mid][m - 1])
l = mid + 1;
}
}
int main()
{
int n = 4;
int m = 5;
int a[][MAX] = {{0, 6, 8, 9, 11},
{20, 22, 28, 29, 31},
{36, 38, 50, 61, 63},
{64, 66, 100, 122, 128}};
int k = 31;
findRow(a, n, m, k);
return 0;
}
|
Java
import java.util.*;
public class Main {
static void findRow( int [][] a, int n, int m, int k)
{
int l = 0 , r = n - 1 , mid;
while (l <= r) {
mid = (l + r) / 2 ;
if (k == a[mid][ 0 ])
{
System.out.println( "Found at (" + mid + ","
+ "0)" );
return ;
}
if (k == a[mid][m - 1 ])
{
int t = m - 1 ;
System.out.println( "Found at (" + mid + ","
+ t + ")" );
return ;
}
if (k > a[mid][ 0 ]
&& k < a[mid]
[m - 1 ])
{
binarySearch(a, n, m, k,
mid);
return ;
}
if (k < a[mid][ 0 ])
r = mid - 1 ;
if (k > a[mid][m - 1 ])
l = mid + 1 ;
}
}
static void binarySearch( int [][] a, int n, int m, int k,
int x)
{
int l = 0 , r = m - 1 , mid;
while (l <= r) {
mid = (l + r) / 2 ;
if (a[x][mid] == k) {
System.out.println( "Found at (" + x + ","
+ mid + ")" );
return ;
}
if (a[x][mid] > k)
r = mid - 1 ;
if (a[x][mid] < k)
l = mid + 1 ;
}
System.out.println( "Element not found" );
}
public static void main(String args[])
{
int n = 4 ;
int m = 5 ;
int a[][] = { { 0 , 6 , 8 , 9 , 11 },
{ 20 , 22 , 28 , 29 , 31 },
{ 36 , 38 , 50 , 61 , 63 },
{ 64 , 66 , 100 , 122 , 128 } };
int k = 31 ;
findRow(a, n, m, k);
}
}
|
Python3
def findRow(a, n, m, k):
l = 0
r = n - 1
mid = 0
while (l < = r) :
mid = int ((l + r) / 2 )
if (k = = a[mid][ 0 ]):
print ( "Found at (" , mid , "," , "0)" , sep = "")
return
if (k = = a[mid][m - 1 ]):
t = m - 1
print ( "Found at (" , mid , "," , t , ")" , sep = "")
return
if (k > a[mid][ 0 ] and k < a[mid][m - 1 ]):
binarySearch(a, n, m, k, mid)
return
if (k < a[mid][ 0 ]):
r = mid - 1
if (k > a[mid][m - 1 ]):
l = mid + 1
def binarySearch(a, n, m, k, x):
l = 0
r = m - 1
mid = 0
while (l < = r):
mid = int ((l + r) / 2 )
if (a[x][mid] = = k):
print ( "Found at (" , x , "," , mid , ")" , sep = "")
return
if (a[x][mid] > k):
r = mid - 1
if (a[x][mid] < k):
l = mid + 1
print ( "Element not found" )
n = 4
m = 5
a = [[ 0 , 6 , 8 , 9 , 11 ], [ 20 , 22 , 28 , 29 , 31 ], [ 36 , 38 , 50 , 61 , 63 ], [ 64 , 66 , 100 , 122 , 128 ]]
k = 31
findRow(a, n, m, k)
|
C#
using System;
public class GFG
{
static void findRow( int [,] a, int n, int m, int k)
{
int l = 0, r = n - 1, mid;
while (l <= r) {
mid = (l + r) / 2;
if (k == a[mid,0])
{
Console.WriteLine( "Found at (" + mid + ","
+ "0)" );
return ;
}
if (k == a[mid,m - 1])
{
int t = m - 1;
Console.WriteLine( "Found at (" + mid + ","
+ t + ")" );
return ;
}
if (k > a[mid,0]
&& k < a[mid,m - 1])
{
binarySearch(a, n, m, k,
mid);
return ;
}
if (k < a[mid,0])
r = mid - 1;
if (k > a[mid,m - 1])
l = mid + 1;
}
}
static void binarySearch( int [,] a, int n, int m, int k,
int x)
{
int l = 0, r = m - 1, mid;
while (l <= r) {
mid = (l + r) / 2;
if (a[x,mid] == k) {
Console.WriteLine( "Found at (" + x + ","
+ mid + ")" );
return ;
}
if (a[x,mid] > k)
r = mid - 1;
if (a[x,mid] < k)
l = mid + 1;
}
Console.WriteLine( "Element not found" );
}
static public void Main ()
{
int n = 4;
int m = 5;
int [,] a = { { 0, 6, 8, 9, 11 },
{ 20, 22, 28, 29, 31 },
{ 36, 38, 50, 61, 63 },
{ 64, 66, 100, 122, 128 } };
int k = 31;
findRow(a, n, m, k);
}
}
|
Javascript
<script>
var MAX = 100;
function binarySearch(a, n, m, k, x)
{
var l = 0, r = m - 1, mid;
while (l <= r)
{
mid = (l + r) / 2;
if (a[x][mid] == k)
{
document.write( "Found at (" + x + "," + mid + ")<br>" );
return ;
}
if (a[x][mid] > k)
r = mid - 1;
if (a[x][mid] < k)
l = mid + 1;
}
document.write( "Element not found<br>" );
}
function findRow(a, n, m, k)
{
var l = 0, r = n - 1, mid;
while (l <= r)
{
mid = parseInt((l + r) / 2);
if (k == a[mid][0])
{
document.write( "Found at (" + mid + ",0)<br>" );
return ;
}
if (k == a[mid][m - 1])
{
var t = m - 1;
document.write( "Found at (" + mid + "," + t + ")<br>" );
return ;
}
if (k > a[mid][0] && k < a[mid][m - 1])
{
binarySearch(a, n, m, k, mid);
return ;
}
if (k < a[mid][0])
r = mid - 1;
if (k > a[mid][m - 1])
l = mid + 1;
}
}
var n = 4;
var m = 5;
var a = [[0, 6, 8, 9, 11],
[20, 22, 28, 29, 31],
[36, 38, 50, 61, 63],
[64, 66, 100, 122, 128]];
var k = 31;
findRow(a, n, m, k);
</script>
|
Time Complexity: O(log n + log m).
Auxiliary Space: O(1)
This method is contributed by Ayushwant Gaurav.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...