Sorting is a way of arranging elements in particular order. Generally, sorting can be done by some specific algorithm. Lexicographical order is the one, which sorts in alphabetical order.
There are
two methods to sort elements in lexicographical order.
- Simple sorting method.
- Arrays.sort() method.
1.Simple
sorting method:
This method reads the set of
inputs. It checks each and every input sequentially and sorts the input in
dictionary order.
#Java
Program to sort lexicographical order
import
java.util.Arrays; //importing the built in package java.util.Arrays
public
class lexicoSort {
public
static void main(String[] args) {
String[] a = {"Quick sort",
"Sequential sort", "Binary sort", "Merge sort"};
//input array
int i=0;
// Loop to sort the elements
for (i= 0; i < a.length - 1; i++) {
for (int j = i + 1; j <
a.length; j++) {
if
(a[i].compareToIgnoreCase(a[j]) > 0) {
String t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
// Print the sorted array of elements
System.out.println("In
lexicographical order:");
for (i=0;i<a.length;i++) {
System.out.println(a[i]);
}
}
}
Here, is
the output for the program.
2.Arrays.sort() method:
This
method uses built in method Arrays.sort(). First, the program reads the input. It
uses arrays.sort() to sort the elements in lexicographical order.
#java
Program to sort the elements in lexicographical order in Arrays.sort() method
import
java.util.Arrays; //importing built in packagr
public
class lexicoSort1 {
public static void main(String[] args) {
String[] a = {"Quick sort",
"Sequential sort", "Binary sort", "Merge sort"};
//input
Arrays.sort(a,
String.CASE_INSENSITIVE_ORDER); //Arrays.sort() built in method
System.out.println("In lexicographical
order:"); //Printing the sorted elements
for (int i=0;i<a.length;i++) {
System.out.println(a[i]);
}
}
}
When you
execute this program ,you get the below
output:
These are the methods to sort elements in lexicographical order.
No comments:
Post a Comment