Most efficient way to search a sorted matrix?

后端 未结 9 1468
野的像风
野的像风 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:31

    This is in the vein of Michal's answer (from which I will steal the nice graphic).

    Matrix:

      min ..... b ..... c
        .       .       .
        .  II   .   I   . 
        .       .       .
        d .... mid .... f
        .       .       .
        .  III  .   IV  .
        .       .       .
        g ..... h ..... max
    

    Min and max are the smallest and largest values, respectively. "mid" is not necessarily the average/median/whatever value.

    We know that the value at mid is >= all values in quadrant II, and <= all values in quadrant IV. We cannot make such claims for quadrants I and III. If we recurse, we can eliminate one quadrant at each level.

    Thus, if the target value is less than mid, we must search quadrants I, II, and III. If the target value is greater than mid, we must search quadrants I, III, and IV.

    The space reduces to 3/4 its previous at each step:

    n * (3/4)x = 1

    n = (4/3)x

    x = log4/3(n)

    Logarithms differ by a constant factor, so this is O(log(n)).

    find(min, max, target)
        if min is max
            if target == min
                return min
            else
                return not found
        else if target < min or target > max
            return not found
        else
            set mid to average of min and max 
            if target == mid
                return mid
            else
                find(b, f, target), return if found
                find(d, h, target), return if found
    
                if target < mid
                    return find(min, mid, target)
                else
                    return find(mid, max, target)
    

提交回复
热议问题