Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting a string array length wise

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));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.


>Solution :

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
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading