Find element in 2D sorted sorted array.

0 views
Skip to first unread message

SURI

unread,
Jul 7, 2011, 4:43:25 AM7/7/11
to Freak-Your-Mind [FYM]
May be this older puzzle but worth solving this.

Given 2d sorted array (Sorted by columns and rows), What is the best
way to find an element?

e.g.
55 30 13
44 22 7
12 6 3

Shyam Prakash

unread,
Jul 9, 2011, 3:11:26 AM7/9/11
to Freak-Your-Mind [FYM]
Start at Top Right => current cell

If the "search value == value[current cell]", print found.
If search "value > value[current cell]", move towards left and make it
current cell.
If search "value < value[current cell]", move towards down and make it
current cell.

If it can't progress, print not found.

Worst case Complexity for [m x n] matrix = O(m + n)

Can we apply binary search on this? will have to check.

Thanks
Shyam Velupula

On Jul 7, 1:43 pm, SURI <koorella.s...@gmail.com> wrote:
> May be this older puzzle but worth solving this.
>
> Given2dsorted array (Sorted by columns and rows), What is the best

SURI

unread,
Jul 9, 2011, 10:56:31 AM7/9/11
to Freak-Your-Mind [FYM]
good explanation Shayam,

I guess we cannot apply binary search as it is, since the structure is
not recursive structure. But we can eliminate the (n+m)/4 elements on
first step and recursively solve 3 eligible sub structures of size (n
+m)/4 each INDEPENDENTLY.

Is this approach better than O(m+n) ?

-- SURI

Shyam Prakash Velupula

unread,
Jul 9, 2011, 11:27:19 AM7/9/11
to freak...@googlegroups.com
Yes the approach you mentioned (eliminating one quarter every iteration) will yield better complexity.

On the side note, you played with numbers and my name :-)

No. elements eliminated would be => (n * m) / 4
--
You are limited only by your imagination

SURI

unread,
Jul 9, 2011, 11:42:57 AM7/9/11
to Freak-Your-Mind [FYM]
Ooooops .. It is a typo, Yes it is (n*m)/4.
Reply all
Reply to author
Forward
0 new messages