Answer the question
In order to leave comments, you need to log in
How to use generics to create a method that sorts an array using the "bubble" method?
How to correctly describe a method that sorts an array of numeric data (double, int, etc.) using Generic?
Tried to do something like this:
public <Type extends Number> static void BubbleSort(Type array[]) {
for (int i = array.length - 1; i >= 0; i--)
for (int j = 0; j < i; j++)
if (array[j] > array[j+1]) {
array[j] = array[j] - array[j+1];
array[j+1] = array[j+1] + array[j];
array[j] = array[j+1] - array[j];
}
}
Answer the question
In order to leave comments, you need to log in
And why do you need to do intValue? If your generalization has comparison operators, then it doesn't matter what the value is - let it compare itself.
Implemented like this:
public static <Type extends Comparable<Type>> void BubbleSort(Type array[]) {
Type temp;
for (int i = array.length - 1; i >= 0; i--)
for (int j = 0; j < i; j++)
if (array[j].compareTo(array[j+1]) > 0) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question