searching in 2D sorted matrix
/***
Searching
in a 2D sorted matrix
Write
an efficient algorithm that searches for a value in an n x m table
(two-dimensional array). This table is sorted along the rows and columns — that
is,
Table[i][j]
≤ Table[i][j + 1],
Table[i][j]
≤ Table[i + 1][j]
Two
Solutions:
1)
BS in row/column through column/row
complexity: O(nlogn)
2)
walk-wise linear
complexity: O(n)
***/
#include<iostream>
using namespace std;
#define N 5
#define M 5
//
binary search: time complexity O(m*logn)
bool bs(int *in, int start, int end, int n) {
if (start > end) return false;
int mid = (start + end) / 2;
if (in[mid] == n) return true;
else if (in[mid] > n)
{
if (bs(in, start, mid-1, n)) return true;
} else {
if (bs(in, mid+1, end, n)) return true;
}
return false;
}
bool search2D_b(int (*a)[M], int n) {
for(int i = 0; i<M; i++) {
if(bs(a[i], 0, N-1, n)) return true;
}
return false;
}
bool walk_wise(int (*a)[M], int i, int j, int n) {
if(i>M-1 || j<0) return false;
if(a[i][j] == n) return true;
else if(a[i][j] < n) {
if(walk_wise(a, i+1, j, n)) return true;
} else {
if(walk_wise(a, i, j-1, n)) return true;
}
return false;
}
//walk
wise: start from upper right
bool search2D(int (*a)[M], int n) {
if(walk_wise(a, 0, N-1, n)) return true;
else return false;
}
void main() {
int a[][M] = {{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24,
25}};
if (search2D(a, -1))
{
cout<<"search2D"<<endl;
}
if (search2D_b(a, 22))
{
cout<<"search2D_binary"<<endl;
}
}
Comments
Post a Comment