1. Introduction
Sorting is a fundamental operation in computing. It involves arranging data, especially lists or arrays, in a specific order. In this blog post, we'll see how to sort a list of numbers in Scala using its standard library functions.
2. Program Steps
1. Initialize the Scala environment.
2. Define a list of unsorted numbers.
3. Use the sorted method to sort the list.
4. Print the sorted list.
5. Execute the program.
3. Code Program
object ListSorter {
def main(args: Array[String]): Unit = {
// Define an unsorted sample list of numbers
val unsortedNumbers = List(42, 23, 8, 15, 4, 16)
// Sort the list using the sorted method
val sortedNumbers = unsortedNumbers.sorted
println(s"Unsorted List: $unsortedNumbers")
println(s"Sorted List: $sortedNumbers")
}
}
Output:
Unsorted List: List(42, 23, 8, 15, 4, 16) Sorted List: List(4, 8, 15, 16, 23, 42)
Explanation:
1. Our program is encapsulated within the ListSorter object.
2. We define a sample list named unsortedNumbers containing numbers in random order.
3. To sort the list, we use the sorted method provided by the List collection in Scala.
4. We then print both the unsorted list and the sorted list to the console.
5. As evident from the output, the numbers in the list are sorted in ascending order after the sorted method is applied.
Comments
Post a Comment