NutzCN Logo
问答 对象的选择排序失败排错
发布于 1419天前 作者 qq_412bd180 1084 次浏览 复制 上一个帖子 下一个帖子
标签:
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

排序失败 问题在哪里呢?谢谢

5 回复

算法题。。。 加日志啦

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=new Student[]{stu,stu2,stu3,stu4};
		selectSort(students);
		printArray(students);
		
		System.out.println();
		
		//这样初始化算法起作用了
		Student[] d = new Student[4];
        d[0] = new Student("D",90);
        d[1] = new Student("C",100);
        d[2] = new Student("B",95);
        d[3] = new Student("A",95);
        selectSort(d);
        printArray(d);
      
	}

两种初始化有什么区别呢 为什么一个没排序 一个排序了
谢大佬

你填的值不一样

是呀 把上面的初始化替换为下面的就可以了
这样更糊涂了,算法不是不管数据有序无序都应该返回正确的结果呀,哪里错了吗?

添加回复
请先登陆
回到顶部