Skip to content

Instantly share code, notes, and snippets.

@fancellu
Last active September 14, 2021 20:32
Show Gist options
  • Select an option

  • Save fancellu/ccffd26cf7ce4e274511e5054b5d6591 to your computer and use it in GitHub Desktop.

Select an option

Save fancellu/ccffd26cf7ce4e274511e5054b5d6591 to your computer and use it in GitHub Desktop.
// Top and bottom N max/min items from an Array, with no need to sort
----------
541
141
18
----------
540
16
----------
-7
2
16
----------
17
540
----------
10000000
9999999
9999998
----------
10000000
9999999
9999998
----------
0
1
2
// Top and bottom N max/min items from an Array, with no need to sort
object TopBottomN extends App {
def bottomN(a: Array[Int], n: Int): Array[Int] = {
val smallestVals = Array.fill(n)(Int.MaxValue)
a.foreach { number =>
var inserted=false
(n - 1 to 0 by -1).foreach { pos =>
if (smallestVals(pos) > number && !inserted) {
(0 to pos - 1).foreach { x => smallestVals(x) = smallestVals(x + 1) }
smallestVals(pos) = number
inserted=true
}
}
}
smallestVals.filterNot(_==Int.MaxValue).reverse
}
def topN(a: Array[Int], n: Int): Array[Int] = {
val largestVals = Array.fill(n)(Int.MinValue)
a.foreach { number =>
var inserted=false
(n - 1 to 0 by -1).foreach { pos =>
if (largestVals(pos) < number && !inserted) {
(0 to pos - 1).foreach { x => largestVals(x) = largestVals(x + 1) }
largestVals(pos) = number
inserted=true
}
}
}
largestVals.filterNot(_==Int.MinValue).reverse
}
println("-"*10)
topN(Array(141, 1, 17, -7, 18, 541), 3).foreach(println)
println("-"*10)
topN(Array(16, 540), 3).foreach(println)
println("-"*10)
bottomN(Array(131, 2, 16, -7, 18, 542), 3).foreach(println)
println("-"*10)
bottomN(Array(17, 540), 3).foreach(println)
val bigNum=10000000
println("-"*10)
topN((0 to bigNum).toArray, 3).foreach(println)
println("-"*10)
topN((bigNum to 0 by -1).toArray, 3).foreach(println)
println("-"*10)
bottomN((0 to bigNum).toArray, 3).foreach(println)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment