title: Efficient way to take the minimum/maximum n values and indices from a matrix using NumPy
body: <p>What's an efficient way, given a NumPy matrix (2D array), to return the minimum/maximum <code>n</code> values (along with their indices) in the array?</p>
  
  <p>Currently I have:</p>
  
  <pre><code>def n_max(arr, n):
      res = [(0,(0,0))]*n
      for y in xrange(len(arr)):
          for x in xrange(len(arr[y])):
              val = float(arr[y,x])
              el = (val,(y,x))
              i = bisect.bisect(res, el)
              if i &gt; 0:
                  res.insert(i, el)
                  del res[0]
      return res
  </code></pre>
  
  <p>This takes three times longer than the image template matching algorithm that <code>pyopencv</code> does to generate the array I want to run this on, and I figure that's silly.</p>