Java Program to Sort Elements in Lexicographical Order (Dictionary Order)

In this program, you’ll learn to sort the element words in lexicographical order using a for loop and if else in Java.

Example: Program to Sort Strings in Dictionary Order

  1. public class Sort {
  2. public static void main(String[] args) {
  3. String[] words = { "Ruby", "C", "Python", "Java" };
  4. for(int i = 0; i < 3; ++i) {
  5. for (int j = i + 1; j < 4; ++j) {
  6. if (words[i].compareTo(words[j]) > 0) {
  7. // swap words[i] with words[j[
  8. String temp = words[i];
  9. words[i] = words[j];
  10. words[j] = temp;
  11. }
  12. }
  13. }
  14. System.out.println("In lexicographical order:");
  15. for(int i = 0; i < 4; i++) {
  16. System.out.println(words[i]);
  17. }
  18. }
  19. }

When you run the program, the output will be:

In lexicographical order:
C
Java
Python
Ruby

In the above program, the list of 5 words to sorted are stored in a variable, words.

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

If the return value of compareTo() is greater than 0, it has to be swapped in position, i.e. words[i] comes after words[j]. So, in each iteration, words[i] contains the earliest word.

Execution Steps
IterationInitial wordsijwords[]
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" }
Final{ "C", "Java", "Ruby", "Python" }23{ "C", "Java", "Python", "Ruby" }