Ask Sawal

Discussion Forum
Notification Icon1
Write Answer Icon
Add Question Icon

How to find alphabetical order in java?

2 Answer(s) Available
Answer # 1 #
  • Get the required string.
  • Convert the given string to a character array using the toCharArray() method.
  • Sort the obtained array using the sort() method of the Arrays class.
  • Convert the sorted array to String by passing it to the constructor of the String array.
[2]
Edit
Query
Report
Aashif Ponnada
PLUG CUTTING MACHINE OPERATOR
Answer # 2 #

Example:

Approach: Brute-Force Approach

The idea is to compare the strings on the basis of their unicode and swap them in accordance with the returned int value based on the comparison between the two strings using compareTo() method.

In the input, the user has to enter the number of names and the names and on the output, it will sort and display them in alphabetical order. For this, we are going to use the compareTo() method and compare one string with the rest of the strings.

CompareTo() is used to compare two strings lexicographically. Each character of both strings is converted into its unicode value. Lexicographical order is nothing but alphabetical order.

This method returns an int data-type which is based on the comparison between the two string. If it returns>0 then the parameter passed to compareTo() method is lexicographically first whereas if returns < 0 then string calling the method is lexicographically correct.

Steps

Below is the implementation of the above approach:

Time Complexity: O(N2)

Approach: Inbuilt Sort function

Below is the implementation of the above approach:

Time Complexity: O(n log n)

[0]
Edit
Query
Report
Gheorghe McRobb
School Nursing