Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to sort the array words in lexicographically ascending order and also use the compareTo() to compare strings.

What I have tried:

I did the following:
public static void main(String[] args) {
  int i,j;
  String key;
  String[] inputArray = {"Sailor"};
  System.out.println(Arrays.toString(inputArray));
  for (j = 1; j < inputArray.length; j++) { 
    key = inputArray[j];
    i = j - 1;
    while (i >= 0) {
      if (key.compareTo(inputArray[i]) > 0) {
        break;
      }
      inputArray[i + 1] = inputArray[i];
      i--;
    }
    inputArray[i + 1] = key;
    System.out.println(Arrays.toString(inputArray));
  }
  System.out.println(Arrays.toString(inputArray));
}
Posted
Updated 19-Jan-23 12:45pm
Comments
Richard Deeming 19-Jan-23 5:56am    
Why not use the build-in sorting method? Eg:
Arrays (Java Platform SE 7 )[^]

1 solution

I did a quick google search and found a great article for you that covers this in detail: Lexicographical Order Java - Javatpoint[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900