public class InsertSort {
public static <E extends Comparable<E>> void inserytSort(E[] arr){
for (int i = 0; i < arr.length; i++) {
// 实现[0, i)中的有序排序
for (int j = i; j - 1 > 0 ; j --) {
//这里的j - 1 > 0;是要保证前面的那个数是一定要有的,如果前面那个数小于当前这个数,就执行交换,否则直接break;
if(arr[j].compareTo(arr[j - 1]) < 0)
swap(arr, j, j - 1);
else
break;
}
}
}
private static <E> void swap(E[] arr,int i,int j) {
E temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
Student[] students = {new Student("lili", 100),
new Student("xiaoxiao", 98),
new Student("jilinggou", 55)};
SelectionSort.sort(students);
for(Student student: students)
System.out.println(student + " ");
}
}
//注意这里的Comparable<>的类型是一个学生生类
public class Student implements Comparable<Student> {
private String name;
private int score;
public Student(String name,int score) {
this.name = name;
this.score = score;
}
@Override
public String toString() {
return String.format("Student(name: %s,score: %d)", name, score);
}
//equals是Object父类的一个函数,这里是覆盖是equals的方法,因此传进去的也应该是Object
public boolean equals(Object student){
if(this == student)
return true;
if(this == null)
return false;
if (this.getClass() != student.getClass() )
return false;
else {
Student student1 = (Student) student;
//忽略大小写,也可查找
return this.name.toLowerCase().equals(student1.name.toLowerCase());
}
}
public int compareTo(Student student){
return this.score - student.score;
}
}
排序结果