排序算法:让数据有序
原理
先把最小的拿出来
剩下的,再把最小的拿出来剩下的,再把最小的拿出来
每次选择还没处理的元素里最小的元素。
代码
public class SelectionSort {
private SelectionSort(){}
public static <E extends Comparable<E>> void sort(E[] arr){
for(int i = 0; i < arr.length; i ++){
//选择arr[i...n)中的最小值的索引
int minIndex = i;
for(int j = i; j < arr.length; j ++){
if(arr[j].compareTo(arr[minIndex])<0)
minIndex = j;
}
swap(arr, i ,minIndex);
}
}
private static <E> void swap(E[] arr ,int i , int j ){
E t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public static void main(String[] args) {
Integer[] arr ={1, 4, 2, 3, 6, 5};
SelectionSort.sort(arr);
for(int e:arr)
System.out.print(e+" ");
System.out.println();
Student[] students = {new Student("Alice",98),
new Student("Bobo",100),
new Student("Charles",66)};
SelectionSort.sort(students);
for (Student student:students)
System.out.print(student+" ");
System.out.println();
}
}
Student.java
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 int compareTo(Student another){
// if(this.score<another.score)
// return -1;
// else if(this.score==another.score)
// return 0;
return this.score-another.score;
}
@Override
public boolean equals(Object student){
if (this == student)
return true;
if (student==null)
return false;
if (this.getClass() != student.getClass())
return false;
Student another = (Student)student;
return this.name.equals(another.name);
}
@Override
public String toString(){
return String.format("Student(name: %s, score: %d)",name,score);
}
}
复杂度
O(n^2)