English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program sorts elements in alphabetical order

Comprehensive Collection of Kotlin Examples

In this program, you will learn to use for loops and if else statements in Kotlin to sort elements in alphabetical order.

Example: Program to sort strings in alphabetical order

fun main(args: Array<String>) {
    val words = arrayOf("Ruby", "C", "Python", "Java")
    for (i in 0..2) {
        for (j in i + 1..3) {
            if (words[i].compareTo(words[j]) > 0) {
                // words[i] and words[j] are swapped 
                val temp = words[i]
                words[i] = words[j]
                words[j] = temp
            }
        }
    }
    println("Sorted according to dictionary order:")
    for (i in 0..3) {
        println(words[i])
    }
}

When running the program, the output is:

Sorted according to dictionary order:
C
Java
Python
Ruby

In the above program, the words to be sorted are5The list of words is stored in the variable word.

Then, we traverse each word (words [i]) and compare it with all the words after it in the array (words [j]). This is done by using the compareTo() method of the string.

If the return value of compareTo() is greater than 0, it must be swapped in position, that is, words[i] after words[j]. Therefore, in each iteration, words[i] contains the earliest word.

Execution Steps
IterationInitial Wordijwords[]
1{ "Ruby", "C", "Python", "Java" }01{ "C", "Ruby", "Python", "Java" }
2{ "C", "Ruby", "Python", "Java" }02{ "C", "Ruby", "Python", "Java" }
3{ "C", "Ruby", "Python", "Java" }03{ "C", "Ruby", "Python", "Java" }
4{ "C", "Ruby", "Python", "Java" }12{ "C", "Python", "Ruby", "Java" }
5{ "C", "Python", "Ruby", "Java" }13{ "C", "Java", "Ruby", "Python" }
Finally{ "C", "Java", "Ruby", "Python" }23{ "C", "Java", "Python", "Ruby" }

This is the equivalent Java code:Java Program Sorts Words in Dictionary Order

Comprehensive Collection of Kotlin Examples