One of the most typical interview questions in Java is to sort a string in ascending order. The interviewer may request that you sort the text in ascending order without utilizing any built-in Java methods.
In this post, I'll show you how to arrange sentences in ascending order. I'll start by separating all of the words from the phrase, then compare their lengths and rank them by word length.
Write a Java programme to sort the sentences in ascending order.
package in .learnjavaskill;
public class AscendingOrder
{
public static void main(String[] args)
{
String input = "The Best Way To Get Started Is To Quit Talking And Begin Doing - Walt Disney";
String[] words = input.split(" "); // splitting words using space and assigning into array or string
for (int i = 0; i < words.length; i++) // looping through all the words till last word
{
for (int j = 0; j < words.length - 1; j++) // looping through all the words from index position zero to length -1.
{
if (words[j].length() > words[j + 1].length()) // comparing the current word to the +1 positon word, swapping both index positions if the +1 positon word is shorter than the current word length.
{
String temp = words[j];
words[j] = words[j + 1];
words[j + 1] = temp;
}
}
}
System.out.println("Ascending order of \"" + input + "\" is ");
for (String word: words)
{
System.out.print(word + " "); // Arrays of words are printed
}
}
}
Output of the above program look like below
Accending order of "The Best Way To Get Started Is To Quit Talking And Begin Doing" is To Is To The Way Get And Best Quit Walt Begin Doing Disney Started Talking
Conclusion
Accending order of "The Best Way To Get Started Is To Quit Talking And Begin Doing" is To Is To The Way Get And Best Quit Walt Begin Doing Disney Started Talking
In this article, we have seen how to sort a string of sentences in ascending order by splitting each word of the sentence.
Keep learning and keep growing.