I would like to know whether is there any isSorted()
function exist or not in scala.
Question: check whether List[Int]
is sorted or not, If not remove smallest number and do again till List[Int]
become sorted?
I want only 1 or 2 line program.
You can compare each pair in the input sequence for lists containing more than 1 item:
def isSorted[T](s: Seq[T])(implicit ord: Ordering[T]): Boolean = s match {
case Seq() => true
case Seq(_) => true
case _ => s.sliding(2).forall { case Seq(x, y) => ord.lteq(x, y) }
}
It's not the best solution but you can use sorted
method on list and then compare it with original one;
def sorted(l: List[Int]): Boolean = l == l.sorted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With