English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use for loops and if using Java, sort elements by alphabetical order.
public class Sort { public static void main(String[] args) { String[] words = { "Ruby", "C", "Python", "Java" }; for(int i = 0; i < 3; ++i) { for (int j = i + 1; j < 4; ++j) { if (words[i].compareTo(words[j]) > 0) { // words[i] and words[j] swap String temp = words[i]; words[i] = words[j]; words[j] = temp; } } } System.out.println("In alphabetical order:"); for(int i = 0; i < 4; i++) { System.out.println(words[i]); } } }
When running the program, the output is:
In alphabetical order: C Java Python Ruby
In the above program, the word to be sorted5The 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 string's compareTo() method.
If the return value of compareTo() is greater than 0, an exchange must be made on the position, that is, word [i] after word [j]. Therefore, in each iteration, the word [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" } |
Final | { "C", "Java", "Ruby", "Python" } | 2 | 3 | { "C", "Java", "Python", "Ruby" } |