Arrange words according to their length
Solution 1:
Perhaps this is what you were looking for. Using minimal external classes, this simply sorts the array of words in ascending order based on their length first and then alphabetically if those lengths are equal It uses a variant
of what is known as a selection sort. It is a basic sort and quite often used as an introduction to sorting. But it is not very efficient.
- read in the string and split based on spaces (I modified your regex to allow 1 or more spaces).
- then use nested loops to iterate thru the list, comparing lengths.
- if the word indexed by the
outer
loop (i
) is longer than the word indexed by theinner
loop (j
), swap the words. - else if equal length compare words to each other and sort alphabetically (the String class implements the Comparable interface).
- when both loops are finished, the array will be sorted in
- then you can just iterate over the result building a string of words separated by spaces.
public class AccordingToLength {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String str = sc.nextLine();
String arr[] = str.split("\\s+");
for (int i = 0; i < arr.length-1; i++) {
int outer = arr[i].length();
for (int j = i + 1; j < arr.length; j++) {
int inner = arr[j].length();
if (outer > inner || outer == inner && arr[i].compareTo(arr[j]) > 0) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
outer = inner; // outer has new length (what was just swapped)
}
}
}
String result = "";
for (String word : arr) {
result += word + " ";
}
System.out.println(result);
}
}
for input = "if a day now any easy when new test is done do den deed none";
this prints
a do if is any day den new now deed done easy none test when
Solution 2:
There are multiple ways to solve this problem. The two most convenient ways are.
-
If you are allowed to use streams and comparator, then you can achieve it in a single line.
Arrays.stream(arr) .sorted(Comparator .comparing(String::length) .thenComparing(Function.identity())) .forEach(System.out::println);
-
Using Arrays.sort() to sort the actual array elements.
Arrays.sort(arr, (o1, o2) -> { if (o1.length() > o2.length()) { return 1; } else if (o2.length() > o1.length()) { return -1; } else { return o1.compareTo(o2); } }); System.out.println(Arrays.toString(arr));
-
If you don't want to use java provided APIs and data structures, you can implement a different version of bubble sort.
boolean isSwapped; for (int i = 0; i < arr.length - 1; i++) { isSwapped = false; for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j].length() > arr[j + 1].length() || arr[j].length() == arr[j + 1].length() && arr[j].compareTo(arr[j + 1]) > 0) { swap(arr, j, j + 1); isSwapped = true; } } if (!isSwapped) break; }