NthHighestNumberWithTailRec

Sudarshan Kasar
Feb 12, 2024

--

object NthHighestValue extends App {
val inputSeq = Seq(2, 5, 1, 1, 6)

val descendingSeq = inputSeq.sorted((x: Int, y: Int) => if (x > y) -1 else if (x == y) 0 else 1)

println(findNthHighestvalue(descendingSeq, 2))

import scala.annotation.tailrec
@tailrec
def findNthHighestvalue(inputSeq: Seq[Int], nth: Int = 1): Int = {
if(inputSeq.size == nth)
inputSeq.last
else findNthHighestvalue(inputSeq.slice(0, inputSeq.size - 1), nth)
}

}
#Scala #tailrec @secondhighestnumber @2ndhighestNumber 

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sudarshan Kasar
Sudarshan Kasar

No responses yet

Write a response