/** * 检查 a 是否小于 b */ publicbooleanless(Comparable a, Comparable b){ return a.compareTo(b) < 0; }
/** * 交换 c 中索引为 i 和 j 的元素 */ publicvoidexch(Comparable[] c, int i, int j){ Comparable t = c[i]; c[i] = c[j]; c[j] = t; }
/** * 检查 c 是否已排序 */ publicvoidisSorted(Comparable[] c){ for (int i = 1; i < c.length; i++>) { if (less(c[i], c[i - 1])) { thrownew RuntimeException("Not Sorted"); } } }
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassSelection{ publicstaticvoidsort(Comparable[] com){ int n = com.length; for (int i = 0; i < n; i++) { int min = i; for (int j = i + 1; j < n; j++) { if (less(com[j], com[min])) { min = j; } } exch(com, min, i); } } }
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * 使用 apache RandomUtils 生成测试数据 */ publicstaticvoidmain(String[] args){ Comparable[] random = new Comparable[20]; for (int i = 0; i < 20; i++) { random[i] = RandomUtils.nextInt(1, 10); } sort(random); for (int i = 0; i < 20; i++) { System.out.print(random[i]); if (i != random.length - 1) { System.out.print(" | "); } } isSorted(random); }