- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Kotlin Program to Sort Elements in Lexicographical Order (Dictionary Order)
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