w3resource

Scala function: Check if a list is sorted


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


Before you start!

To solve this problem, you should have a basic understanding of:

  • Scala lists and how to define them.
  • Comparing elements in a list using relational operators.
  • How the sliding method works for iterating over consecutive elements.
  • The concept of implicit parameters in Scala.
  • Using the forall method to check conditions on all elements in a list.

Try before looking at the solution!

Think about how you can check if a list is sorted in ascending order:

  • How can you compare each element with the next one in the list?
  • What happens if the list has only one element or is empty?
  • How does the Ordering trait help in comparing generic types?
  • Can you solve this using recursion or a loop instead of built-in methods?

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.