Computer >> Computer tutorials >  >> Programming >> Java

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


In this article, we will understand how to sort the elements of an array in Lexicographical order in Java. The lexicographical order is a generalization of the alphabetical order of the dictionaries to sequences.

Below is a demonstration of the same −

Input

Suppose our input is −

Aplha Beta Gamma Delta

Output

The desired output would be −

Aplha Beta Delta Gamma

Algorithm

Step1- Start
Step 2- Declare three integers: I, j, array_length
Step 3- Declare a string array
Step 4- Prompt the user to enter the array_length value/ define the array_length
Step 5- Prompt the user to enter the words of the string array/ define the string array
Step 4- Read the values
Step 5- Run a for-loop, using the swap method, arrange the words using the compareTo
function. Store the values.
Step 6- Display the result
Step 7- Stop

Example 1

public class Main {
   public static void main(String[] args) {
      String[] my_input = { "Aplha", "Beta", "Gamma", "Delta" }; ;
      int i, j, array_length;
      array_length = 4;
      System.out.println("The array of string is defined as ");
      for(i = 0; i < array_length; i++) {
         System.out.println(my_input[i]);
      }
      for(i = 0; i < array_length - 1; ++i) {
         for (j = i + 1; j < array_length; ++j) {
            if (my_input[i].compareTo(my_input[j]) > 0) {
               String temp = my_input[i];
               my_input[i] = my_input[j];
               my_input[j] = temp;
            }
         }
      }
      System.out.println("The words in lexicographical order is:");
      for(i = 0; i < 4; i++) {
         System.out.println(my_input[i]);
      }
   }
}

Output

The array of string is defined as
Aplha
Beta
Gamma
Delta
The words in lexicographical order is:
Aplha
Beta
Delta
Gamma

Example 2

import java.io.*;
public class LexicographicalOrder {
   public static void
   sortData(String my_array[]){
      for (int i = 0; i < my_array.length; i++) {
         for (int j = i + 1; j < my_array.length; j++) {
            if (my_array[i].compareToIgnoreCase(my_array[j])< 0) {
               String my_temp = my_array[i];
               my_array[i] = my_array[j];
               my_array[j] = my_temp;
            }
         }
      }
   }
   public static void printData(String my_array[]){
      for (String my_string : my_array)
      System.out.print(my_string + " ");
      System.out.println();
   }
   public static void main(String[] args){
      String my_array[] = { "Aplha", "Beta", "Gamma", "Delta" };
      System.out.println("Required packages have been imported");
      System.out.println("The Lexicographical Order data is");
      sortData(my_array);
      printData(my_array);
   }
}

Output

Required packages have been imported
The Lexicographical Order data is
Aplha Beta Delta Gamma