使用排序算法实现对所有引用类型数据的比较(冒泡+选择排序) ,自定义Person类进行测试

使用排序算法实现对所有引用类型数据的比较(冒泡+选择排序) ,自定义Person类进行测试。

  1. 方法声明为public  void sortArr(Object arr[]){  }。
  2. 方法中首先输出排序前数组内容,然后进行排序,最后输出排序后数组内容。
  3. 可以是冒泡排序或其他算法实现,不直接调用Java提供的方法实现排序。

思路:任意类实现Comparable接口来实现该引用数据类型的元素排序,在sort()方法中将Object强转成Comparable实现两个对象的比较。

冒泡:

public class Student implements Comparable{
    private String name;
    private int age;
    private Double score;

    public Student() {
    }

    public Student(String name, int age, Double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Double getScore() {
        return score;
    }

    public void setScore(Double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        Student stu = (Student)o;
        if (Double.compare(this.score, stu.score)==0){
            return -Integer.compare(this.age, stu.age);
        }
        return -Double.compare(this.score, stu.score);
    }
}
public class Sort {
    public static void arrSort(Comparable[] arr){
        for (int i = 0; i < arr.length-1; i++) {
            boolean flag = true;
            for (int j = 0; j < arr.length-1-i; j++) {
                if (arr[j].compareTo(arr[j+1])==1){
                    Comparable temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    flag = false;
                }

            }
            if (flag){
                break;
            }
        }
    }
}
public class Test {
    public static void main(String[] args) {
        Student stu1 = new Student("小明", 18, 60.1);
        Student stu2 = new Student("小红", 17, 99.1);
        Student stu3 = new Student("朋友", 19, 60.1);
        Student stu4 = new Student("是我的", 16, 60.9);
        Student[] arr = {stu1,stu2,stu3,stu4};
        Sort.arrSort(arr);
        for (Student student : arr) {
            System.out.println(student);
        }
    }
}

 

你可能感兴趣的:(JAVA重难点及常见BUG)