Dec 25, 2008

A 2D array is such that each row in it is in ascending order and each column is in ascending order. How will you search for an element in this array?

A 2D array is such that each row in it is in ascending order and each column is in ascending order. How will you search for an element in this array? (O(n) is enough)
Say the desired element is "key".

Start from the bottom left, if the element there equal, key has been found. If it is lesser than key, move to the right else move to the upper row.

Bool Func(int a[][n], int n, int key)
{
Int i=n-1, j=0;
While(i>=0&&j<=n-1)
{
If(keyi--;
else if(key>a[i][j])
j++;
else return true;
}
Return false;
}

No comments:

Post a Comment