I am required to sort an array with selection sort. I wanted it to to sort a string array in increasing order of length of its specific string elements.
It doesn't give the required output.
String[] a = sc.nextLine().trim().split(" ");
for (int i = 0;i< a.length-1;i++) {
String min = a[i];
for (int j = i + 1; j < a.length; j++) {
if (a[j].length() < min.length()) min = a[j];
}
String t = a[i];
a[i] = min;
min = t;
}
I tried to observe the array elements by using System.out.println(Arrays.toString(a));
Here's what i got and what i want:
On inputting,
Hello Java Its me
Observed Output
me me me me
Expected Output
me Its Java Hello
that is according to the length of a
's string elements.
You didn't correctly swap. You need to save the index of min element and swap a[i]
and a[minIdx]
.
String[] a = sc.nextLine().trim().split(" ");
for (int i = 0;i< a.length-1;i++) {
String min = a[i];
int minIdx = i; // <-- remember min index
for (int j = i + 1; j < a.length; j++) {
if (a[j].length() < min.length()) {
min = a[j];
minIdx = j; // <-- update min index
}
}
String t = a[i];
a[i] = min;
a[minIdx] = t; // <-- proper swap
}