N
N
NameOf Var2017-02-09 21:43:31
Java
NameOf Var, 2017-02-09 21:43:31

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]; 
                }
    }

To get the value of the array[i] variable, I must write array[i].intValue() or array[i].doubleValue(), etc., but I want to sort an array of any numeric data and it is not known in advance which type is fed into method.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2017-02-09
@GavriKos

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.

N
NameOf Var, 2017-02-10
@hax

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 question

Ask a Question

731 491 924 answers to any question