Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array of strings in reverse alphabetical order in Java

Tags:

java

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;
    }
}
like image 285
Quacky Avatar asked Dec 08 '12 16:12

Quacky


1 Answers

Don't reinvent the wheel -

String[] strs = {"a", "b", "d", "c", "e"};

Arrays.sort(strs, Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER));

System.out.println(Arrays.toString(strs));
[e, d, c, b, a]
like image 63
arshajii Avatar answered Nov 07 '22 11:11

arshajii