English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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.
Iteration | Initial Word | i | j | words[] |
---|---|---|---|---|
1 | { "Ruby", "C", "Python", "Java" } | 0 | 1 | { "C", "Ruby", "Python", "Java" } |
2 | { "C", "Ruby", "Python", "Java" } | 0 | 2 | { "C", "Ruby", "Python", "Java" } |
3 | { "C", "Ruby", "Python", "Java" } | 0 | 3 | { "C", "Ruby", "Python", "Java" } |
4 | { "C", "Ruby", "Python", "Java" } | 1 | 2 | { "C", "Python", "Ruby", "Java" } |
5 | { "C", "Python", "Ruby", "Java" } | 1 | 3 | { "C", "Java", "Ruby", "Python" } |
Finally | { "C", "Java", "Ruby", "Python" } | 2 | 3 | { "C", "Java", "Python", "Ruby" } |
This is the equivalent Java code:Java Program Sorts Words in Dictionary Order