In this tutorial you will learn about the Java Program to Sort Elements in Lexicographical Order and its application with practical example.
In this tutorial, we will learn to create a Program that will Sort Elements in Lexicographical Order using java programming.
Prerequisites
Before starting with this program we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic input/output.
- Basic Java programming.
- Array and Multidimensional Array.
- Loops in java.
- Nested For loop.
- Class and object in java.
What is Lexicographical Order?.
In Mathematics, the terminology lexicographic or lexicographical order is a Alphabetical order or the Dictionary ordered,more generally “elements of a ordered set(ascending order(a-z))”.
What Is Array ?
An Array is a collection of similar data type containing collection of elements (values or variables), each identified by one Array index value, Array is a data structure that hold collection of elements.
Java Program to Sort Elements in Lexicographical Order.
In this program we will sort elements in Lexicographical Order using nested for loop. We would first declared and initialized the required variables. Next, we would initializing array with elements after that we arrange Elements in Lexicographical Order.
Here we takes 4 elements and arrange them in lexicographical order using nested for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Main { public static void main(String[] args) { String[] s = { "Php", "C", "Python", "Java" }; // initializing array.. for(int i = 0; i < 3; ++i) { for (int j = i + 1; j < 4; ++j) { if (s[i].compareTo(s[j]) > 0) { // arranging in lexical order.. String temp = s[i]; s[i] = s[j]; s[j] = temp; } } } // Printing in lexical order... System.out.println("In lexicographical order:"); for(int i = 0; i < 4; i++) { System.out.println(s[i]); } } } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- s = it will holds 4 elements.
- temp= holds temporary values.
- i and j= for iterations.
In this program we will find Lexicographical Order of given elements .first of all in this statement we will take 4 elements.
then we apply sorting method to arrange these elements in Lexicographical Order.
After arraigning elements in Lexicographical Order. then at last we will display the elements that we arranged in Ascending order.
Finally the result will be is in sorted or lexicographical order .