|
|
@@ -2,55 +2,38 @@ package com.cyl.algorithrms.sort;
|
|
|
|
|
|
/**
|
|
|
* 选择排序
|
|
|
+ * 时间复杂度:O(n^2)
|
|
|
+ * 空间复杂度:O(1)
|
|
|
+ *
|
|
|
+ * 与冒泡排序相比,基本上一致,依然是两两比较,但是减少了交换次数(不是立刻交换,而是遍历一次后再交换)
|
|
|
*/
|
|
|
public class Selection {
|
|
|
|
|
|
- public static void sort(Comparable[] a) {
|
|
|
- //将a[]按升序排列
|
|
|
- int N = a.length;
|
|
|
- for (int i = 0; i < N; i++) {
|
|
|
- int min = i;
|
|
|
- for (int j = i + 1; j < N; j++) {
|
|
|
- if(less(a[j], a[min])) {
|
|
|
- min = j;
|
|
|
+ public static void sort(Comparable[] a, boolean ascending) {
|
|
|
+ //获取数组长度
|
|
|
+ int len = a.length;
|
|
|
+ //排序方向:1 升序;-1 降序
|
|
|
+ int compVal = ascending ? 1 : -1;
|
|
|
+ //第一个循环:控制遍历次数
|
|
|
+ for (int i = 0; i < len; i++) {
|
|
|
+ //用于记录当前的待排序元素
|
|
|
+ int idx = i;
|
|
|
+ //第二个循环:控制待排序的范围 (待遍历的范围)
|
|
|
+ // 待排序的元素下标 i、[i+1, len - 1]
|
|
|
+ // idx=i 即当前循环开始时的待排序元素
|
|
|
+ // j=i+1 即下一个要比较的元素
|
|
|
+ // len-1 即0基础表示时,数组的最后一个元素,j < len 与 j <= len-1 等价
|
|
|
+ for (int j = i + 1; j < len; j++) {
|
|
|
+ // a[j] > a[j+1] 即 升序 (true, 1)
|
|
|
+ // a[j] < a[j+1] 即 降序 (false, -1)
|
|
|
+ if(a[idx].compareTo(a[j]) == compVal) {
|
|
|
+ idx = j;
|
|
|
}
|
|
|
- exch(a, i, min);
|
|
|
}
|
|
|
+ // 找到符合目标的元素后进行交换
|
|
|
+ Comparable tmp = a[i];
|
|
|
+ a[i] = a[idx];
|
|
|
+ a[idx] = tmp;
|
|
|
}
|
|
|
}
|
|
|
-
|
|
|
- private static boolean less(Comparable v, Comparable w) {
|
|
|
- return v.compareTo(w) < 0;
|
|
|
- }
|
|
|
-
|
|
|
- private static void exch(Comparable[] a, int i, int j) {
|
|
|
- Comparable t = a[i];
|
|
|
- a[i] = a[j];
|
|
|
- a[j] = t;
|
|
|
- }
|
|
|
-
|
|
|
- private static void show(Comparable[] a) {
|
|
|
- // 在单行中打印数组
|
|
|
- for (int i = 0; i < a.length; i++) {
|
|
|
- System.out.print(a[i] + " ");
|
|
|
- }
|
|
|
- System.out.println();
|
|
|
- }
|
|
|
-
|
|
|
- public static boolean isSorted(Comparable[] a) {
|
|
|
- // 测试数组元素是否有序
|
|
|
- for (int i = 1; i < a.length; i++) {
|
|
|
- if(less(a[i], a[i-1])) {
|
|
|
- return false;
|
|
|
- }
|
|
|
- }
|
|
|
- return true;
|
|
|
- }
|
|
|
-
|
|
|
- public static void main(String[] args) {
|
|
|
- String[] a = "SORTEXAMPLE".split("");
|
|
|
- sort(a);
|
|
|
- assert isSorted(a);
|
|
|
- show(a);
|
|
|
- }
|
|
|
}
|