0

I'm learning algorithms in Java and I'm working on a self project of remaking (any would be great) sort algorithm to support any type instead int, double, float, string, etc values only.

Example:

public static int[] insertionSort(int[] target) {
    for (int firstUnsortedIndex = 1; firstUnsortedIndex < target.length; firstUnsortedIndex++ ) {
        int newUnsortedElement = target[firstUnsortedIndex];
        int i;
        // looking for insertion place from right to left (till index 0) and sorted partition element is greater than unsorted element
        for (i = firstUnsortedIndex; i > 0 && target[i - 1] > newUnsortedElement; i --) {
            // shifting higher or equal values to the right of sorted partition on each iteration
            target[i] = target[i - 1];
        }
        target[i] = newUnsortedElement;
    }
    return target;
}

and currently I have 'generic' I think method bellow , is it true?

public static <T> T[] genericInsertionSort(T[] target) {    
    for (int firstUnsortedIndex = 1; firstUnsortedIndex < target.length; firstUnsortedIndex++) {
        T newUnsortedElement = target[firstUnsortedIndex];
        int i;
        for (i = firstUnsortedIndex; i > 0 && (int) target[i - 1] > (int) newUnsortedElement; i --) {
            target[i] = target[i - 1];
        }
        target[i] = newUnsortedElement;
    }
    return target;
}

and when I use it:

public static void main(String[] args) {
    System.out.print(Arrays.toString(genericInsertionSort( new int[] {1, 0, 8, 5, 2} )));
}

I get The method genericInsertionSort(T[]) in the type InsertionSort is not applicable for the arguments (int[])

What am I missing? Am I remaking sort algorithm right? Could you help me please.

Any tips, sources much appreciated.

Thanks

lpkej
  • 445
  • 6
  • 23
  • 1
    A generic type parameter cannot be a *primitive* type. It's a limit of the language. Sorry, you can't do it. --- If you look at the list of methods available for [`java.util.Arrays`](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html), you'll see that all the methods have many overloads, one for `T` and one for each primitive type. It even has the `sort()` methods you're trying to implement. – Andreas May 25 '20 at 14:48
  • You could use `new Integer[] {1, 0, 8, 5, 2}`. But your `genericInsertionSort` casts each element to `int` anyways, so a) this wouldn't work and b) it is not generic at all. – f1sh May 25 '20 at 14:49
  • 2
    Also: Declaring the sort method as taking a generic array as an argument and then casting the elements of that array to `int` makes little sense. If you want to write the sort method to accept parameters that aren't `int` then you cannot just continue treating every value as an `int` in that method. – OH GOD SPIDERS May 25 '20 at 14:50

0 Answers0