Algorithm


  1. Input:

    • Accept an array or a collection of elements as input that needs to be sorted lexicographically.
  2. Lexicographical Sort Algorithm:

    • Use a sorting algorithm to arrange the elements in lexicographical order. Commonly used sorting algorithms include:
      • Bubble Sort: Compare each pair of adjacent elements and swap them if they are in the wrong order. Repeat this process until the entire array is sorted.
      • Selection Sort: Find the minimum element in the unsorted part of the array and swap it with the first unsorted element. Repeat this process until the entire array is sorted.
      • Arrays.sort() Method: If you are using an array, you can directly use the Arrays.sort() method, which internally uses a highly optimized version of merge sort or TimSort.
  3. Output:

    • Print or return the sorted array or collection.

 

Code Examples

#1 Code Example- Program to Sort Strings in Dictionary Order

Code - Java Programming

class Main {
  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) {

          // swap words[i] with words[j[
          String temp = words[i];
          words[i] = words[j];
          words[j] = temp;
        }
      }
    }

    System.out.println("In lexicographical order:");
    
    for(int i = 0; i  <  4; i++) {
      System.out.println(words[i]);
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
In lexicographical order:
C
Java
Python
Ruby
Advertisements

Demonstration


Java Programing Example to Sort Elements in Lexicographical Order (Dictionary Order)-DevsEnv