Right now I'm working on an assignment and we are give a list of words to be sorted alphabetically, and we have to use the compareTo method. I need it to sort the entire list so it can then be printed. I've been struggling with this final part for about an hour now, can somebody lend an insight into why this code isn't working at all?
public static void selectionSort(final Comparable[] array)
{
if (array == null)
{
throw new NullPointerException("The array is null.");
}
for(int i = 0; i < (array.length - 1); i++)
{
Comparable thisWord = array[i];
int num = i;
while(thisWord.compareTo(array[num]) > 0)
{
Comparable tmp = array[num];
array[num] = thisWord;
array[i] = tmp;
num++;
}
}
}
I might be way off, either way I don't feel like I'm making any progress. Any help would be much appreciated!!
You want a generic Comparable
type like T extends Comparable<? super T>
T extends Comparable<? super T>
, but I would start with a generic swap
private static <T> void swap(T[] array, int i, int j) {
if (i != j) {
T tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
Then you can use that to perform a selection sort like
public static <T extends Comparable<? super T>> void selectionSort(T[] array) {
if (array == null) {
throw new NullPointerException("The array is null.");
}
for (int i = 0; i < array.length - 1; i++) {
int num = i; // <-- num will be the min
for (int j = i + 1; j < array.length; j++) {
if (array[j].compareTo(array[num]) < 0) {
num = j; // <-- j is less than num, set num to j
}
}
swap(array, num, i); // <-- swap the elements at num and i
}
}
And then you can run it like
public static void main(String argv[]) {
String[] arr = { "z", "b", "a" };
selectionSort(arr);
System.out.println(Arrays.toString(arr));
}
Which outputs
[a, b, z]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.