Friday, March 29, 2013

Find an element in a sorted 2D array using saddleback search in C

Consider the following sorted 2D array and you want to find an element .
1  2  3
4  6  9
7  8  10

Rows and columns are sorted and assume that its elements are unique . if u want to find an element ,the simplest and easiest approach is to use saddleback search algorithm . This algorithm starts searching from first row last element . If the value is less than the element that you are searching move left otherwise move down . Continue this step until you find the element .

Example.

1) Start from the first row last element(3) .
2) Consider you want to find the element k=8 . It is bigger than 3 , so go down to the second row last element 9.
3) K=8 value is less than 9 . so move left and check boundary condition . Element here is 6 which is less than k . so again move down and check boudary condition .
4) Now the k value is found .

Code:(in C)
void saddleBackSearch(int **a,int rows,int cols,int k)
{
int i=0,j=cols-1;
while(1)
{
if(k==a[i][j])
{
printf("%d %d",i,j);
break;
}
if(k<a[i][j])
{
j=j-1;
if(j<0)
{
printf("Not Found");
break;
}
}
else
{
i=i+1;
if(i>rows-1)
{
printf("Not Found");
break;
}
}
}
}
view raw saddle.c hosted with ❤ by GitHub

Please let me know if you have any questions .

No comments: