Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check whether given List[Int] is sorted in scala?

Tags:

scala

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.

like image 790
sk1007 Avatar asked Oct 25 '15 11:10

sk1007


2 Answers

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) }
}
like image 100
Lee Avatar answered Sep 28 '22 03:09

Lee


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
like image 26
Fatih Donmez Avatar answered Sep 28 '22 02:09

Fatih Donmez