w3resource

Scala function: Check if a list is sorted

Scala Function Exercise-10 with Solution

Write a Scala function to check if a given list is sorted in ascending order.

Sample Solution:

Scala Code:

object ListSortChecker {
  def isSortedAscending[A](list: List[A])(implicit ord: Ordering[A]): Boolean = {
    list.sliding(2).forall { case List(a, b) => ord.lteq(a, b) }
  }

  def main(args: Array[String]): Unit = {
    val list1 = List(1, 2, 3, 4, 5, 6)
    val list2 = List(4, 2, 5, 1, 6, 3)
    println("List1: "+list1)
    println(s"Is List1 is sorted in ascending order? ${isSortedAscending(list1)}")
    println("List2: "+list2)
    println(s"Is List2 is sorted in ascending order? ${isSortedAscending(list2)}")
  }
}

Sample Output:

List1: List(1, 2, 3, 4, 5, 6)
Is List1 is sorted in ascending order? true
List2: List(4, 2, 5, 1, 6, 3)
Is List2 is sorted in ascending order? false

Scala Code Editor :

Previous: Check if a number is a perfect square.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.