How to  Sort Alphabetical Order in Array  in Java

How to Sort Alphabetical Order in Array in Java

·

1 min read

what is Alphabetical Order

According to ASCII rules

[numbers][capital letters][lowercase letters]

0 ~ 9, A ~ Z, a ~ z

Codes

  • Time complexity : O(n log n)
  • Space complexity : O(1)

    For List

      Collections.sort(List<String>_values);
    

    For Array

      Arrays.sort(String[]array);
    

  • Time complexity : O(n^2)
  • Space complexity : O(1)

Logic for Array

    public static String[] LexicalOrder(String[] words) {
        int n = words.length;
        for (int i = 0; i < n - 1; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (words[i].compareTo(words[j]) > 0) {
                    String temp = words[i];
                    words[i] = words[j];
                    words[j] = temp;
                }
            }
        }
        return words;
    }