Most efficient way to search a sorted matrix?

后端 未结 9 1539
野的像风
野的像风 2020-12-29 14:02

I have an assignment to write an algorithm (not in any particular language, just pseudo-code) that receives a matrix [size: M x N] that is sorted in a way that all of it\'s

9条回答
  •  臣服心动
    2020-12-29 14:41

    Your matrix looks like this:

    a ..... b ..... c
    . .     . .     .
    .   1   .   2   . 
    .     . .     . .
    d ..... e ..... f
    . .     . .     .
    .   3   .   4   .
    .     . .     . .
    g ..... h ..... i
    

    and has following properties:

    a,c,g < i  
    a,b,d < e
    b,c,e < f
    d,e,g < h
    e,f,h < i
    

    So value in lowest-rigth most corner (eg. i) is always the biggest in whole matrix and this property is recursive if you divide matrix into 4 equal pieces.

    So we could try to use binary search:

    1. probe for value,
    2. divide into pieces,
    3. choose correct piece (somehow),
    4. goto 1 with new piece.

    Hence algorithm could look like this:

    input: X - value to be searched
    until found
     divide matrix into 4 equal pieces
     get e,f,h,i as shown on picture
     if (e or f or h or i) equals X then 
       return found
     if X < e then quarter := 1
     if X < f then quarter := 2
     if X < h then quarter := 3
     if X < i then quarter := 4
     if no quarter assigned then 
        return not_found
     make smaller matrix from chosen quarter 
    

    This looks for me like a O(log n) where n is number of elements in matrix. It is kind of binary search but in two dimensions. I cannot prove it formally but resembles typical binary search.

提交回复
热议问题