(简单)选择排序.gif

1. 基础版

每次从剩余待排元素中找到最小值放到待排元素最前面,共n-1轮

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. int n = sc.nextInt();
  6. int[] a = new int[n];
  7. for (int i = 0; i < n; i++)
  8. a[i] = sc.nextInt();
  9. for (int i = 0; i < a.length - 1; i++) {
  10. for (int j = i + 1; j < a.length; j++) {
  11. if (a[j] < a[i]) {
  12. int t = a[i];
  13. a[i] = a[j];
  14. a[j] = t;
  15. }
  16. }
  17. }
  18. for (int i = 0; i < n; i++) {
  19. System.out.print(a[i] + " ");
  20. }
  21. }
  22. }

2. 基础优化版

不是在选数过程中进行交换,而是找到最小元素后再交换

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. int n = sc.nextInt();
  6. int[] a = new int[n];
  7. for (int i = 0; i < n; i++)
  8. a[i] = sc.nextInt();
  9. for (int i = 0; i < a.length - 1; i++) {
  10. int mIdx = i;
  11. for (int j = i + 1; j < a.length; j++) {
  12. if (a[j] < a[mIdx])
  13. mIdx = j;
  14. }
  15. if (mIdx != i) {
  16. int t = a[i];
  17. a[i] = a[mIdx];
  18. a[mIdx] = t;
  19. }
  20. }
  21. for (int i = 0; i < n; i++) {
  22. System.out.print(a[i] + " ");
  23. }
  24. }
  25. }

复杂度

时间复杂度:严格O(n)
空间复杂度:O(1)