update
String[] a = sc.nextLine().trim().split(" ");
for (int i = 0; i < a.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j].length() < a[minIndex].length()) {
minIndex = j;
}
}
String temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
System.out.println(Arrays.toString(a));
This code first initializes a variable minIndex to the current index i.
It then iterates through the rest of the array, comparing the length of each string element with the length of the string at minIndex.
If it finds a string with a shorter length, it updates minIndex to point to that string.
After the inner loop finishes, it swaps the string at i with the string at minIndex, effectively placing the string with the shortest length in the first position.
The outer loop repeats this process until all strings have been sorted in increasing order of their lengths.
The code you provided is not sorting the array in increasing order of length of its specific string elements. Instead, it is swapping the elements in the array such that the shortest string is at the beginning of the array.
To sort the array in increasing order of length of its specific string elements, you can use the Arrays.sort() method and pass a custom comparator that compares the lengths of the strings. Here's an example:
String[] a = sc.nextLine().trim().split(" ");
Arrays.sort(a, new Comparator<String>() {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
System.out.println(Arrays.toString(a));
This will give you the expected output:
me Its Java Hello
Arrays.sort(a, Comparators.comparingInt(String::length))?