(1)sorter
public class Sorter<T> {
public void sort(T[] arr, Comparator<T> comparator) {
for(int i=0; i<arr.length - 1; i++) {
int minPos = i;
for(int j=i+1; j<arr.length; j++) {
minPos = comparator.compare(arr[j],arr[minPos])==-1 ? j : minPos;
}
swap(arr, i, minPos);
}
}
void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
(2)main
public class Main {
public static void main(String[] args) {
Cat[] a = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
//Dog[] a = {new Dog(3), new Dog(5), new Dog(1)};
Sorter<Cat> sorter = new Sorter<>();
//Sorter<Dog> sorter = new Sorter<>();
sorter.sort(a,new CatHeightComparator());
//sorter.sort(a,new CatWeightComparator());
//sorter.sort(a,new DogComparator());
System.out.println(Arrays.toString(a));
}
}
(3) Cat
public class Cat {
int weight, height;
public Cat(int weight, int height) {
this.weight = weight;
this.height = height;
}
@Override
public String toString() {
return "Cat{" +
"weight=" + weight +
", height=" + height +
'}';
}
}
(4)Comparator
public interface Comparator<T> {
int compare(T o1, T o2);
}
(5)CatHeightComparator
public class CatHeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if(o1.height > o2.height) return -1;
else if (o1.height < o2.height) return 1;
else return 0;
}
}
(6)CatWeightComparator
public class CatWeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if(o1.weight < o2.weight) return -1;
else if (o1.weight > o2.weight) return 1;
else return 0;
}
}
(7)Dog
public class Dog {
int food;
public Dog(int food) {
this.food = food;
}
@Override
public String toString() {
return "Dog{" +
"food=" + food +
'}';
}
}
(8) DogComparator
public class DogComparator implements Comparator<Dog> {
@Override
public int compare(Dog o1, Dog o2) {
if(o1.food < o2.food) return -1;
else if (o1.food > o2.food) return 1;
else return 0;
}
}