I'm sure everyone has seen this at one time or another. I'm having trouble with the selection sort class.

It should take this input:
apple
Apple
Zone
apple

And return it as:
1:a:Apple
0:a:apple
3:a:apple
2:z:Zone

I'm getting it as #0,1,3,2.

here is the snippet I'm working with. Thanks for any help.

static class SelectionSort {

        static int[] sortValues(String[][] dataArray, int wordCount) {
            int y;
            int z;
            int temp;
            int minIndex;

            String[] tempArray;
            // Array that holds the sorted element's indexes
            // initialize the indexes array
            int[] sortedIndexArray = new int[wordCount];
            for (y = 0; y < wordCount; y++) {
                sortedIndexArray[y] = y;
            }
            //sort
            for (z = y - 1; z < wordCount; z++) {

                minIndex = z;

                for (y = z - 1; y < wordCount; y++) {
                    if (dataArray[y][0].compareTo(dataArray[minIndex][0]) < 0) {
                        minIndex = y;
                    }
                }

                if (minIndex != z) {
                    temp = sortedIndexArray[z];
                    sortedIndexArray[z] = sortedIndexArray[minIndex];
                    sortedIndexArray[minIndex] = temp;

                    tempArray = dataArray[z];
                    dataArray[z] = dataArray[minIndex];
                    dataArray[minIndex] = tempArray;

                }
            }
            return sortedIndexArray;
        }
    }

I recommend that you give your variables more meaningful names than y and z. It will help you keep track of them when you are trying to find a problem. If y and z were simply normal index iterators in the for loops then they wouldn't need meaningful names because their meanings would simply be obvious, but in this case y is being used in three distinct for loops and it's not instantly clear what its value should be.

For example, in the loop that starts on line 17, I am concerned that when z is assigned the value y - 1, y has the value wordCount, so that for loop will have only one iteration with z = wordCount - 1. That seems unlikely to be correct behaviour, but I'm not sure what other value you intended for y to have at that point. If y had a more meaningful name, all this confusion would become clear and you wouldn't have made a mistake.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.