Skip to content

Instantly share code, notes, and snippets.

@kaja47
Created July 7, 2013 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaja47/5944287 to your computer and use it in GitHub Desktop.
Save kaja47/5944287 to your computer and use it in GitHub Desktop.
They said I can't have fast TopK, but I proved them wrong. And they stabbed me in the stomach.
def topKEstaimateMin(arr: Array[Double], k: Int): Double = {
import java.lang.Integer
val upperK = Integer.highestOneBit(k) * 2 // must be higher than k, otherwise can produce wrong minimum
val bits = Integer.numberOfTrailingZeros(upperK)
val mask = (1 << bits) - 1
var i = 0
val maximums = new Array[Double](upperK)
while (i < arr.length) {
val pos = i & mask
val m = maximums(pos)
val a = arr(i)
maximums(pos) = (if (m < a) a else m)
i += 1
}
var min = Double.PositiveInfinity
var j = 0
while (j < upperK) {
min = (if (maximums(j) < min) maximums(j) else min)
j += 1
}
return min
}
@jsuchal
Copy link

jsuchal commented Jul 8, 2013

Kukam na to uz pekne dlho a fakt nechapem. Mozes hodit nejaky odkaz na to aku fintu pouzivas? Lebo tento zapis algoritmu nedokazem rozlustit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment