Sort the words in lexicographical order in Java


The words are sorted in lexicographical order or dictionary order. This means that the words are alphabetically ordered based on their component alphabets. An example of this is given as follows.

The original order of the words is
Tom
Anne
Sally
John
The lexicographical order of the words is
Anne
John
Sally
Tom

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      String[] words = { "Peach", "Orange", "Mango", "Cherry", "Apple" };
      int n = 5;
      System.out.println("The original order of the words is: ");
      for(int i = 0; i < n; i++) {
         System.out.println(words[i]);
      }
      for(int i = 0; i < n-1; ++i) {
         for (int j = i + 1; j < n; ++j) {
            if (words[i].compareTo(words[j]) > 0) {
               String temp = words[i];
               words[i] = words[j];
               words[j] = temp;
            }
         }
      }
      System.out.println("
The lexicographical order of the words is: ");       for(int i = 0; i < n; i++) {          System.out.println(words[i]);       }    } }

Output

The original order of the words is:
Peach
Orange
Mango
Cherry
Apple
The lexicographical order of the words is:
Apple
Cherry
Mango
Orange
Peach

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements