1. 先把最小的拿出来
  2. 剩下的,再把最小的拿出来
  3. 剩下的,再把最小的拿出来
  4. 每次选择还没处理的元素里最小的元素
  • 新开辟一个数组? 占用了额外空间。
  • 选择排序算法是可以进行原地排序的算法

    原地排序

  • arr[i…n)未排序, arr[0…i) 已排序 => 循环不变量

  • arr[i…n)中的最小值要放到arr[j]的位置

image.png
image.png
数据规模扩大10倍,耗时增加了100倍,可以看出是n^2级别的时间复杂度

  1. public class SelectionSort {
  2. private SelectionSort() {
  3. }
  4. public static <E extends Comparable<E>> void sort(E[] arr) {
  5. for (int i = 0; i < arr.length; i++) {
  6. //选择arr[i...n)中最小值的索引
  7. int minIndex = i;
  8. for (int j = i; j < arr.length; j++) {
  9. if (arr[j].compareTo(arr[minIndex]) < 0) {
  10. minIndex = j;
  11. }
  12. }
  13. swap(arr, i, minIndex);
  14. }
  15. }
  16. private static <E> void swap(E[] arr, int i, int j) {
  17. E temp = arr[i];
  18. arr[i] = arr[j];
  19. arr[j] = temp;
  20. }
  21. public static void main(String[] args) {
  22. Integer[] arr = {1, 5, 7, 4, 6, 9};
  23. SelectionSort.sort(arr);
  24. for (int i : arr) {
  25. System.out.print(i + "\t");
  26. }
  27. System.out.println();
  28. Student[] students = {new Student("Alice", 22), new Student("Bobo", 18), new Student("Jack", 33)};
  29. SelectionSort.sort(students);
  30. for (Student student : students) {
  31. System.out.println(student);
  32. }
  33. }
  34. }
  35. public class Student implements Comparable<Student> {
  36. private String name;
  37. private int score;
  38. public Student(String name) {
  39. this.name = name;
  40. }
  41. public Student(String name, int score) {
  42. this.name = name;
  43. this.score = score;
  44. }
  45. @Override
  46. public boolean equals(Object o) {
  47. if (this == o) {
  48. return true;
  49. }
  50. if (o == null) {
  51. return false;
  52. }
  53. if (this.getClass() != o.getClass()) {
  54. return false;
  55. }
  56. Student another = (Student) o;
  57. return this.name.equals(another.name);
  58. }
  59. @Override
  60. public int compareTo(Student o) {
  61. return this.score - o.score;
  62. }
  63. @Override
  64. public String toString() {
  65. return "Student(" +
  66. "name='" + name + '\'' +
  67. ", score=" + score +
  68. ')';
  69. }
  70. }