Search code examples
javaarraysfilefor-loopswap

Sorting Method Not Sorting Properly


This method is supposed to sort the words from a given file in alphabetical order after it is selected. Everything is working except it doesn't properly sort it. The input file reads "kundu is a man kundu man", but no matter what I try I get "[is, kundu, a, man, kundu, man]".

I tried taking away the "-1" and the "+1" but that did nothing to help.

private String[] selectionSort(String[] stringArray)
{
    for(int j = 0; j < stringArray.length - 1; j++)
    {
        int min = j;
        for(int k = j + 1; k < stringArray.length; k++)
        {
            if(stringArray[k].compareTo(stringArray[min]) < 0)
                min = k;

            swap(stringArray, j, min); //this method swaps the words 
                                       // by using a temp
            //swap(intArray, j, min);
        }
    }

    return stringArray;
}


private void swap(String [] stringArray, int i, int j) //swap method
{
     String temp = stringArray[i];
     stringArray[i] = stringArray [j];
     stringArray[j] = temp;
}

Solution

  • Your swap call should be after the inner loop. Like,

    private String[] selectionSort(String[] stringArray) {
        for (int j = 0; j < stringArray.length - 1; j++) {
            int min = j;
            for (int k = j + 1; k < stringArray.length; k++) {
                if (stringArray[k].compareTo(stringArray[min]) < 0) {
                    min = k;
                }
            }
            swap(stringArray, j, min);
        }
        return stringArray;
    }
    

    After that, with no other changes and your input, I get

    [a, is, kundu, kundu, man, man]