Reputation: 123
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.
Upvotes: 1
Views: 115
Reputation: 616
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
Upvotes: 2
Reputation: 509
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
}
Upvotes: 3