First of all, your compile error comes from the type of the swap variable. On the line swap = ar[j];, you are trying to put a value of type E into a variable of type int. That is a type error. To fix that, you need to change the type of the swap variable by doing this:
E swap;
Now, if you want to sort objects of a generic type, you need to know how to compare them. In Java, there's two ways to do this. Either the type has to implement the Comparable interface, or you need to take an object of type Comparator as a parameter. Using a Comparator is more flexible because it makes the caller able to easily sort the same type in multiple ways (for example in chronological order and reversed chronological order).
To make your code work with a Comparable, you need to place a type constraint on your type parameter. Like this:
public static <E extends Comparable<E>> void sort(E[] ar){
E swap;
for (int i = 0; i < ar.length; i++) {
for (int j = i; j < ar.length - 1; j++) {
// Now you can use compareTo because E is a Comparable.
// Also note the "< 0" because compareTo returns an int.
if (ar[j].compareTo(ar[j + 1]) < 0) {
swap = ar[j];
ar[j] = ar[j + 1];
ar[j + 1] = swap;
}
}
}
}
Here's how you would do it with a Comparator:
public static <E> void sort(E[] ar, Comparator<E> comparator){
E swap;
for (int i = 0; i < ar.length; i++) {
for (int j = i; j < ar.length - 1; j++) {
if (comparator.compare(ar[j], ar[j + 1]) < 0) {
swap = ar[j];
ar[j] = ar[j + 1];
ar[j + 1] = swap;
}
}
}
}
You can call the function by creating Comparators like this:
// Sorting integers in ascending order.
sort(intArr, Comparator.naturalOrder());
// Sorting persons in descending order by age.
sort(personArr, Comparator.comparing(Person::getAge).reversed());
Note: Your code doesn't actually sort anything yet, because your algorithm is wrong. That is left for you to fix :)
Eis not anint. What do you expect?