0

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!!

  • 1
    check this http://stackoverflow.com/questions/27410241/sorting-a-list-alphabetically-using-compareto-method?rq=1 – Saravana Sep 24 '16 at 03:55

1 Answers1

0

You want a generic Comparable type like 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]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249