Sort Elements in Lexicographical Order in Kotlin



In this article, we will understand how to sort the elements of an array in Lexicographical order in Kotlin. The lexicographical order is a generalization of the alphabetical order of the dictionaries to sequences.

Below is a demonstration of the same ?

Suppose our input is ?

Alpha Beta Gamma Delta

The desired output would be ?

Delta Gamma Beta Alpha

Algorithm

  • Step 1 ? Start

  • Step 2 ? Declare three integers: I, j and temp

  • Step 3 ? Declare a string array myInput

  • Step 4 ? Run a for-loop, using the swap method, arrange the words in the descending order of their starting letter. Store the values.

  • Step 5 ? Display the array

  • Step 6 ? Stop

Example 1

In this example, we will Sort Elements in Lexicographical Order. This is like Dictionary Order. First, create a Kotlin array using the arrayOf() method ?

val myInput = arrayOf("Alpha", "Beta", "Gamma", "Delta")

Use a nested for loop to sort the array elements ?

for (i in 0..2) { for (j in i + 1..3) { val temp = myInput[i] myInput[i] = myInput[j] myInput[j] = temp } }

Display the array elements in lexicographical order

for (i in 0..3) { println(myInput[i]) }

Let us now see the complete example to sort elements in lexicographical order

fun main() { val myInput = arrayOf("Alpha", "Beta", "Gamma", "Delta") println("The input array is defined as: ") for (element in myInput) { println(element) } for (i in 0..2) { for (j in i + 1..3) { val temp = myInput[i] myInput[i] = myInput[j] myInput[j] = temp } } println("
The lexicographical order of the array is:"
) for (i in 0..3) { println(myInput[i]) } }

Output

The input array is defined as:
Alpha
Beta
Gamma
Delta

The lexicographical order of the array is:
Delta
Gamma
Beta
Alpha

Example 2

In this example, we will sort Elements in Lexicographical Order (Dictionary Order) ?

fun main() { val myInput = arrayOf("Alpha", "Beta", "Gamma", "Delta") println("The input array is defined as: ") for (element in myInput) { println(element) } lexicographicalOrder(myInput) } fun lexicographicalOrder(myInput: Array<String>) { for (i in 0..2) { for (j in i + 1..3) { val temp = myInput[i] myInput[i] = myInput[j] myInput[j] = temp } } println("
The lexicographical order of the array is:"
) for (i in 0..3) { println(myInput[i]) } }

Output

The input array is defined as:
Alpha
Beta
Gamma
Delta

The lexicographical order of the array is:
Delta
Gamma
Beta
Alpha
Updated on: 2022-10-13T13:27:29+05:30

375 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements