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