3
\$\begingroup\$

The goal is to have a function that can sort a series of all object types that implement the comparable interface. I'm not trying to improve the performance of the sort. I'm only trying to optimize my use of generics.

I currently use T extends whatever and T[], however I was also considering to use T extends whatever and ArrayList<T>. Is one more preferable over the other or are both approaches just trash? If you have other remarks please tell me I'm here to learn :)

    public static void main( String[] args )
    {
        String[] stringList = {"hello", "this", "is", "a", "test", "ab", "aaa","aba"};
 
        Quicksort.sort(stringList, 0, stringList.length - 1);
        System.out.println( Arrays.toString(stringList));
    }
public class Quicksort{
    private static <T extends Comparable<T>> int partitioning(T[] arr, int start, int end) {
        T pivot = arr[end];
        int balancePoint = start; // everything that's smaller to the left of this, the rest to the right

        for (int i = start; i < end; i++) {
            if(arr[i].compareTo(pivot)<=0) {
                Arrayswap.genericArraySwap(arr, i, balancePoint);
                balancePoint++;
            }
        }

        Arrayswap.genericArraySwap(arr, end, balancePoint);

        return balancePoint;
    }

    public static <T extends Comparable<T>> void sort(T[]a, int i, int j) {
        if (i>=j) {
            return;
        }

        int pivot = partitioning(a, i, j);

        sort(a, i, pivot-1);
        sort(a, pivot+1, j);
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Er, there is a space too many after main( and before the closing ) - not consistent ;) \$\endgroup\$ Oct 19, 2021 at 22:31

1 Answer 1

2
\$\begingroup\$

Welcome to Code Review, the use of <T extends Comparable<T>> and T[] looks fine to me and personally I would not change it. The only one thing I am not agree is about the indexes you use to order one array like below :

Quicksort.sort(stringList, 0, stringList.length - 1);

In the java sorting methods from the std library the range to be sorted extends from the starting index, inclusive, to the end index, exclusive, so for me your method should be rewritten in the way that ordering an array arr of length n should be obtained by Quicksort.sort(arr, 0, n).

\$\endgroup\$
2
  • \$\begingroup\$ Hi Thanks for your feedback. Making the last parameter inclusive is indeed more consistent. Thanks again for your time :) \$\endgroup\$
    – BugSquanch
    Oct 16, 2021 at 11:53
  • \$\begingroup\$ @DevShot You are welcome and again good job :) \$\endgroup\$ Oct 16, 2021 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.