Computer Science Canada

Selective Sorting

Author:  a22asin [ Sun Dec 01, 2013 4:17 pm ]
Post subject:  Selective Sorting

Hi, so im trying to use selective sorting to sort an array of strings alphabetically (case -insensitive), where each string is one word. I got this codes from my textbook and i modified it to work with strings. But the array does not sort properly. It seems like it diesnt ignore the cases and it doesnt sort the words properly.

ie.When i print array[0] through array [3] it will do:
Ambro
Aaron
Aach
aba

instead of

aba
Aach
Aaron
Ambro

code:

public static String[] selectionSort(String[] array){
               
                int current = 0;
               
                while(current < array.length){ //need n iterations for n elements
                        //value and index to start with
                        String minValue = array[current];
                        int minIndex = current;
               
                        for(int i = current; i<array.length; i++){
                       
                                //search for smallest value
                                if(array[i].toLowerCase().compareTo(minValue) < 0 ){
                                        minValue = array[i];
                                        minIndex = i;
                                }
                        }
                        //swap current element with smallest element
                        String temp = array[current];
                        array[current] = array[minIndex];
                        array[minIndex] = temp;
                        current++;
               
                }
                return array;
        }


I have a feeling that i have modified the code wrong, but cant seem to find where.

Author:  DemonWasp [ Sun Dec 01, 2013 5:18 pm ]
Post subject:  RE:Selective Sorting

The only problem I see is that your 'minValue' isn't necessarily lower-case. Remember that the .toLowerCase() method generates and returns a new string containing the lower-case value, rather than changing the existing value of the string.

Author:  Zren [ Sun Dec 01, 2013 5:41 pm ]
Post subject:  RE:Selective Sorting

Quote:

aba
Aach
Aaron
Ambro


That's not alphabetical either...

When using compareTo between strings. If you want to sort by case-insentivity, you need both strings that you are comparing to be converted to the same case.

Java:

// Your code
if(array[i].toLowerCase().compareTo(minValue) < 0 ){

// is basically this
if (lowerCaseString.compareTo(mixedCaseString) < 0) {


Edit: (╯?□?)╯︵ ┻━┻)

Author:  a22asin [ Sun Dec 01, 2013 5:49 pm ]
Post subject:  RE:Selective Sorting

oh, i see what i did wrong, i forgot to change minValue to lowercase as well. Thanks.It worded.


: