Given 2D array with integers sorted both horizontally and vertically.
Devise an efficient algorithm to search for key in the 2D array. What is
the complexity ?
Eg. 1 4 7 13
2 5 9 15
3 6 10 16
Eg. 1 4 7 13
2 5 9 15
3 6 10 16
Solution :
Two solutions exists :
(Assume the row is sorted from left to right and column from top to bottom so that the least number is at top-left)
First one is :
Two solutions exists :
(Assume the row is sorted from left to right and column from top to bottom so that the least number is at top-left)
First one is :
- Start from left-bottom
- While within boundary
- If key found print and exit
- If key is smaller move up else move right
- Let M < N (otherwise interchange the usage below)
- for each M 1D arrays do binary search in O(log N)
First :
- Time : O(M + N)
- Space : O(1)
- Time : O(M log N) M < N
- Space : O(1)
Code :
/**
* M rows
* N columns
* (row, col) position of searched key if successful
**/
First method :
bool search_2D(int *input, int M, int N, int key, int *row, int *col){
*row = M-1;
*col = 0;
*col = 0;
while(*row > 0 && *col < N){
int current = *(input + N*(*row) + (*col));
if(key == current)
if(key == current)
return true;
else if(key < current)
}
(*row)--;
else
(*col)++;
return false;
Second method :
bool search_2D(int *input, int M, int N, int key, int *row, int *col){
int increment = 1, total_rows = M, total_cols = N;
if(M > N){
for(*row =0; *row < total_rows; i++){
return false;
}if(M > N){
increment = N;
total_rows = N;
total_cols = M;
}total_rows = N;
total_cols = M;
for(*row =0; *row < total_rows; i++){
*col = 0;
if(search_1D(input + *row, total_cols, key, col, increment)){
}if(search_1D(input + *row, total_cols, key, col, increment)){
return true;
}return false;
bool search_1D(int *input, int N, int key, int *index, int increment){
int low = 0, high = N-1;
while(low <= high){
return false;
}while(low <= high){
*index = (low + high)/2;
int value = *(input + (*index)*(increment));
if(value == key)
}int value = *(input + (*index)*(increment));
if(value == key)
return true;
else if (value < key)
low = *index + 1;
else
high = *index - 1;
return false;
No comments:
Post a Comment