I have to write a selection sort. This is what I came up with
public static void sortString(String[] stringArray) {
int max = DataManager.getArraySizeExcludingNull(stringArray), smallest = 0;
String temp;
for (int i = 0; i < max; i++) {
smallest = i;
for (int j = 0; j < max; j++) {
if (stringArray[j].compareTo(stringArray[smallest]) < 0) {
smallest = j;
}
}
temp = stringArray[i];
stringArray[i] = stringArray[smallest];
stringArray[smallest] = temp;
}
}
I have a list with 45 names (I've checked that max is of size 45 and that each index is a string). The method seems to separate the array in half, in a lexicographically correct order in 2 parts? This is my output.
Kate
Leroy
Nicola
Nancy
Oprah
Peter
Quinton
Richard
Kelly
Sven
Theo
Terry
Violet
Wilma
Zed
Allan
Bob
Steve
Nigel
Neil
Fred
Sally
Glenn
Gary
Heather
Horatio
Ivan
Ingrid
Susy
Lindsay
Mitch
Shelly
David
Kirsten
Sarah
Janet
Barbra
Carrie
Jacob
Elenor
Evan
John
Mike
Josh
Aaron
You need to loop over the rest of the data to find the minimum, not all the data, i.e. j
should start from i+1
, not 0
, otherwise you just end up putting the minimum into the first position, then moving it to the second, then the third and so on, leaving the array completely unsorted, except that the minimum will be at the end.
And using DataManager.getArraySizeExcludingNull(stringArray)
is probably wrong for this problem (judging by the name of the function), as you're treating max
as the last index, not the number of non-null values. You need to simply use stringArray.length
and/or change your function appropriately.