Friday, 15 August 2014

Lexical order, dictionary order, alphabetical order or lexicographical order



The lexicographic or lexicographical order (also known as lexical orderdictionary order,alphabetical order or lexicographic) is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters.

Now the question is how to sort an array elements in lexicographical order? Following example show the way to sort an array in this order.

Example :-

public static void main(String[] args) {

String [] arr=new String[]{"abc","acb","aab","abd","acc","adb","baa","cab","bab"};

sortInLexicographicalOrder(arr);

for(String str : arr){
System.out.println(str);
}
}

public static void sortInLexicographicalOrder(String  strArr[])

{
int k;
boolean flag = true;
String tempStr;
while (flag)
{
flag = false;
for (k = 0; k<strArr.length-1; k++)
{
if (strArr[k].compareToIgnoreCase(strArr[k+1]) > 0)
{
tempStr = strArr [k];
strArr [k] = strArr [k+1]; // swap element with the next element.
strArr [k+1] = tempStr; // store current element with next index.
flag = true;



}

Output :-



No comments:

Post a Comment