Lexicographical order java – Java Program to Sort Elements in Lexicographical Order (Dictionary Order)

Lexicographical order java: Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Program to Sort Elements in Lexicographical Order (Dictionary Order)

In this article we will see how to sort elements in Lexicographical order or dictionary order.

We will see two different approaches to do it.

Method-1 : By using normal sorting technique

We can sort elements in Lexicographical order by using normal sorting technique.

Approach:

  • Here the elements in the array will be compared and sorted by normal sorting technique means each element will be compared with others and will be swapped accordingly.

Program:

class Dictionary
{
  public static void main(String args[]) 
  {

    String[] dict = { "ear", "Ball", "Cat", "Ant", "Dog" };
    
    // this for loop to compare each element with all other elements
    for(int i = 0; i < 4; ++i) 
    {
       // this for loop is to compare 'index-i' element with remaining 'index-j' elemnts
      for (int j = i + 1; j < 5; ++j) 
      {
          // swapping by comparing 'index-i' element with 'index-j' element
        if (dict[i].compareTo(dict[j]) > 0) 
        {

          // swapping dict[i] with dict[j]
          String temp = dict[i];
          dict[i] = dict[j];
          dict[j] = temp;
        }
      }
    }

    System.out.println("In lexicographical order:");
    
    for(int i = 0; i < 5; i++) {
      System.out.println(dict[i]);
    }
  }
}
Output:

Printing in lexicographical order:
Ant
Ball
Cat
Dog
ear

Method-2 : By using sort() method in Arrays class

We can sort elements in Lexicographical order by using normal sorting technique.

Approach:

  • Here the elements in the array will be compared and sorted by inbuilt sort() function present in Arrays class.

Program:

import java.io.*;
import java.util.Arrays;
  
class Dictionary
{
    public static void main(String[] args)
    {
        // String array initialized
        String[] dict = { "Ear", "Bag", "Cat", "Ant", "Dog", "Fan" };
  
        // sorting the elements
        // case insensitive
        Arrays.sort(dict,String.CASE_INSENSITIVE_ORDER);
  
        // after sortin printing the array.
        System.out.println("In lexicographical order:");
        for(int i = 0; i < 5; i++) 
        {
          System.out.println(dict[i]);
        }
    }
}
Output:

In lexicographical order:Ant
Bag
Cat
Dog
Ear

Understand the Programming Language Java and learn the language fastly by using our wide range of Java Programming Examples with Output and try to write programs on your own.

Related Java Programs: