O(n^2)级别的排序算法
优点
-基础
-编码简答,易于实现,简单场景的首选
-特殊情况下,简单的排序算法更加有效
-简单的排序算法衍生出复杂的排序算法
选择排序
public class SelectionSort {
public void selectionSort(int[] arr, int n) {
for (int i = 0; i < n; i++) {
// 寻找[i,n)区间里的最小值
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (a[j].compareTo(a[minIndex]) < 0) {
minIndex = j;
}
temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
}
}
public static void main(String[] args) {
int[] a = {10,9,8,7,6,5,4,3,2,1};
SelectionSort selectionSort = new SelectionSort();
selectionSort.selectionSort(a, a.length);
for (int i : a) {
System.out.print(i);
}
}
}
泛型选择排序
-自定义类Student
public class Student implements Comparable<Student> {
private String name;
private Integer score;
public Student(String name, Integer score) {
super();
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
// Student比较方法,先比较分数再比较名字
@Override
public int compareTo(Student o) {
return this.getScore() != o.getScore() ? this.getScore().compareTo(o.getScore())
: this.getName().compareTo(o.getName());
}
@Override
public String toString() {
return "Student [name=" + name + ", score=" + score + "]";
}
}
-排序算法
public class SelectionSort {
// 实现泛型排序
public static <T extends Comparable<? super T>> void selectionSort(T[] a, int n) {
for (int i = 0; i < n; i++) {
// 寻找[i,n)区间里的最小值
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (a[j].compareTo(a[minIndex])<0) {
minIndex = j;
T temp;
temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
}
}
}
public static void main(String[] args) {
// 泛型时不能采用基本类型
System.out.println("====整型====");
Integer[] a = {10,9,8,7,6,5,4,3,2,1};
selectionSort(a, a.length);
for (int i : a) {
System.out.print(i);
System.out.print(" ");
}
System.out.println();
System.out.println("====双精度====");
Double[] b = {10.1,9.1,8.1,7.1,6.1,5.1,4.1,3.1,2.1,1.1};
selectionSort(b, b.length);
for (Double j : b) {
System.out.print(j);
System.out.print(" ");
}
System.out.println();
System.out.println("====字符串====");
String[] c = {"D","C","B","A"};
selectionSort(c, c.length);
for (String l : c) {
System.out.print(l);
System.out.print(" ");
}
System.out.println();
System.out.println("====学生====");
Student s1 = new Student("d", 10);
Student s2 = new Student("c", 1);
Student s3 = new Student("b", 1);
Student s4 = new Student("a", 1);
Student[] students = {s1,s2,s3,s4};
selectionSort(students, students.length);
for (Student student : students) {
System.out.println(student);
}
}
}
-输出结果
====整型====
1 2 3 4 5 6 7 8 9 10
====双精度====
1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1
====字符串====
A B C D
====学生====
Student [name=a, score=1]
Student [name=b, score=1]
Student [name=c, score=1]
Student [name=d, score=10]