package will.zhang.basic.BSelectSortUsingComparable;

import will.zhang.util.SortTestHelper;

import java.util.Arrays;

/**
 * 对选择排序所做的一个更改
 * 凡是实现了Comparable接口的类
 * 都可以排序
 */
public class SelectionSort {

    /**
     * 不允许产生实例
     */
    private SelectionSort() {}

    public static void sort(Comparable[] arr){
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if(arr[j].compareTo(arr[i]) < 0){
                    SortTestHelper.swap(arr, i, j);
                }
            }
        }
    }

    public static void main(String[] args) {
        //测试int
        Integer[] arr = {5, 9, 8, 7, 10, 6, 3, 0, 2, 1, 4};
        SelectionSort.sort(arr);
        System.out.println(Arrays.toString(arr));

        //测试double
        Double[] d = {5.5, 9.9, 8.8, 7.7, 10.1, 6.6, 3.3, 0d, 2.2, 1.1, 4.4};
        SelectionSort.sort(d);
        System.out.println(Arrays.toString(d));

        //测试character
        Character[] c = {'e','d','a','c','g','f','k','i'};
        SelectionSort.sort(c);
        System.out.println(Arrays.toString(c));

        //测试String
        String[] s = {"e","d","a","c","g","f","k","i"};
        SelectionSort.sort(s);
        System.out.println(Arrays.toString(s));

        //测试自定义对象
        Student[] students = {new Student("Tom", 30), new Student("Cat", 40), new Student("Dog", 99)};
        SelectionSort.sort(students);
        System.out.println(Arrays.toString(students));
    }
}

@@ -352,24 +352,94 @@
 gth; i++) %7B%0A
+            // %E5%AF%BB%E6%89%BE%5Bi, arr.length%5D%E5%8C%BA%E9%97%B4%E9%87%8C%E7%9A%84%E6%9C%80%E5%B0%8F%E5%80%BC%0A            int minIndex = i;%0A
             
@@ -521,17 +521,24 @@
 eTo(arr%5B
-i
+minIndex
 %5D) %3C 0)%7B
@@ -562,38 +562,20 @@
     
-SortTestHelper.swap(arr, i,
+minIndex =
  j
-)
 ;%0A  
@@ -596,32 +596,83 @@
 %7D%0A            %7D%0A
+            SortTestHelper.swap(arr, i, minIndex);%0A
         %7D%0A    %7D%0A

optimize selection sort code