Write a Kotlin Program to Sort Elements in Lexicographical Order

Sorting elements in lexicographical order means arranging them in alphabetical order, just like how words are sorted in a dictionary.

In Kotlin, we can easily achieve this using the built-in sorting function provided by the language.

Here’s a Kotlin program to sort elements in lexicographical order:

fun main() {
    val elements = listOf("banana", "apple", "pear", "orange", "grape")

    val sortedElements = elements.sorted()

    println("Original Elements: $elements")
    println("Sorted Elements: $sortedElements")
}

In this program, we have a list of fruit names stored in the elements variable.

We then use the sorted() function to sort the elements in lexicographical order and store the sorted list in the sortedElements variable.

Finally, we print both the original and sorted lists using the println() function.

The output of this program will be:

Original Elements: [banana, apple, pear, orange, grape]
Sorted Elements: [apple, banana, grape, orange, pear]

As you can see, the elements have been sorted in alphabetical order.

In addition to lists, we can also use the sorted() function to sort arrays, sets, and other collections in lexicographical order.

The sortedDescending() function can also be used to sort elements in reverse lexicographical order.

Overall, sorting elements in lexicographical order is a common task in programming, and Kotlin makes it easy to accomplish.