Most efficient way to search a sorted matrix?

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

    and that's how the sample input looks? Sorted by diagonals? That's an interesting sort, to be sure.

    Since the following row may have a value that's lower than any value on this row, you can't assume anything in particular about a given row of data.

    I would (if asked to do this over a large input) read the matrix into a list-struct that took the data as one pair of a tuple, and the mxn coord as the part of the tuple, and then quicksort the matrix once, then find it by value.

    Alternately, if the value of each individual location is unique, toss the MxN data into a dictionary keyed on the value, then jump to the dictionary entry of the MxN based on the key of the input (or the hash of the key of the input).

    EDIT:

    Notice that the answer I give above is valid if you're going to look through the matrix more than once. If you only need to parse it once, then this is as fast as you can do it:

    for (int i = 0; i

    Apparently my comment on the question should go down here too :|

    @sagar but that's not the example given by the professor. otherwise he had the fastest method above (check the end of the row first, then proceed) additionally, checking the end of the middlest row first would be faster, a bit of a binary search.

    Checking the end of each row (and starting on the end of the middle row) to find a number higher than the checked for number on an in memory array would be fastest, then doing a binary search on each matching row till you find it.

提交回复
热议问题