Click here to Skip to main content
15,794,475 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"};
  for (j = 1; j < inputArray.length; j++) { 
    key = inputArray[j];
    i = j - 1;
    while (i >= 0) {
      if (key.compareTo(inputArray[i]) > 0) {
      inputArray[i + 1] = inputArray[i];
    inputArray[i + 1] = key;
Updated 19-Jan-23 13:45pm
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