Sorting an array of strings in reverse alphabetical order in Java

Posted by Quacky on Stack Overflow See other posts from Stack Overflow or by Quacky
Published on 2012-12-08T16:58:53Z Indexed on 2012/12/08 17:03 UTC
Read the original article Hit count: 143

Filed under:

I've been tasked with turning this code into a reverse sort, but for the life of me cannot figure out how to do it. These are my sort, findlargest and swap methods. I have a feeling I am missing something glaringly obvious here, any help would be really appreciated.

    public static void sort(String[] arr)
    {
        for (int pass = 1; pass < arr.length; pass++)
        {
            int largestPos = findLargest(arr, arr.length - pass);
            if (largestPos != arr.length - pass)
            {
                swap(arr, largestPos, arr.length - pass);
            }
        }
    }

    public static int findLargest(String[] arr, int num)
    {
        int largestPos = 0;
        for (int i = 1; i <= num; i++)
        {
            if (arr[i].compareToIgnoreCase(arr[largestPos]) > 0)
            {
                largestPos = i;
            }
        }
        return largestPos;
    }

    public static void swap(String[] arr, int first, int second)
    {
        String temp = arr[first];
        arr[first] = arr[second];
        arr[second] = temp;
    }
}

© Stack Overflow or respective owner

Related posts about java