public class SelectionSortT<T> {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu=new Student("B",90);
Student stu2=new Student("A",100);
Student stu3=new Student("C",85);
Student stu4=new Student("V",100);
//System.out.println(stu.compareTo(stu));
Student[] students={stu,stu2,stu3,stu4};
selectSort(students);
printArray(students);
}
public static <T extends Comparable<? super T>> void selectSort(T[] arr){
for(int i=0;i<arr.length;i++){
int minIndex=i;
for(int j=i+1;j<arr.length;j++){
if(arr[j].compareTo(arr[minIndex])<0){
minIndex=j;
}
swap(arr,i,minIndex);
}
}
}
public static <T> void swap(T[] arr, int i, int j) {
T t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public static <T> void printArray(T[] arr){
for(T t:arr){
System.out.println(t);
}
}
}
class Student implements Comparable<Student>{
String name;
double score;
Student(String name,double score){
this.name=name;
this.score=score;
}
@Override
public int compareTo(Student o) {
if(this.score==o.score){
return 0;
}else if(this.score>o.score){
return 1;
}else{
return -1;
}
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "name:"+name+",score:"+score;
}
}
输出是
name:B,score:90.0
name:A,score:100.0
name:C,score:85.0
name:V,score:100.0
排序失败 问题在哪里呢?谢谢