Computer >> Computer tutorials >  >> Programming >> Java

Java program to sort words of sentence in ascending order


To sort words of sentence in ascending order, the Java code is as follows −

Example

import java.util.*;
public class Demo{
   static void sort_elements(String []my_str, int n){
      for (int i=1 ;i<n; i++){
         String temp = my_str[i];
         int j = i - 1;
         while (j >= 0 && temp.length() < my_str[j].length()){
            my_str[j+1] = my_str[j];
            j--;
         }
         my_str[j+1] = temp;
      }
   }
   public static void main(String args[]){
      String []my_arr = {"This", "is", "a", "sample"};
      int len = my_arr.length;
      sort_elements(my_arr,len);
      System.out.print("The sorted array is : ");
      for (int i=0; i<len; i++)
      System.out.print(my_arr[i]+" ");
   }
}

Output

The sorted array is : a is This sample

A class named Demo contains a function named ‘sort_elements’. This function iterates through a String and checks the length of every word in the string and arranges them based on their length. In the main function, aString array is defined and its length is assigned to a variable. The ‘sort_elements’ function is called on this string and the sorted array is displayed on the console.