时间复杂度O(n^2)
    Java实现:
    根据最大和最小索引分别实现

    1. public static <E extends Comparable<E>> void sort(E[] nums) {
    2. int length = nums.length;
    3. //nums[0...i]有序 nums[i...n)无序
    4. for (int i = 0; i < length; i++) {
    5. //选择nums中最小值的索引
    6. int minIndex = i;
    7. for (int j = i; j < length; j++) {
    8. if (nums[j].compareTo(nums[minIndex]) < 0) {
    9. minIndex = j;
    10. }
    11. E num = nums[i];
    12. nums[i] = nums[minIndex];
    13. nums[minIndex] = num;
    14. }
    15. }
    16. System.out.println(Arrays.toString(nums));
    17. }
    1. public static <E extends Comparable<E>> void sort2(E[] nums) {
    2. int length = nums.length - 1;
    3. //nums[0...i]无序 nums[i...n)有序
    4. for (int i = length; i >= 0; i--) {
    5. //当前最大索引
    6. int maxIndex = i;
    7. for (int j = i; j >= 0; j--) {
    8. if (nums[j].compareTo(nums[maxIndex]) > 0) {
    9. maxIndex = j;
    10. }
    11. }
    12. swap(nums, i, maxIndex);
    13. }
    14. System.out.println(Arrays.toString(nums));
    15. }
    16. private static <E> void swap(E[] nums, int i, int minIndex) {
    17. E num = nums[i];
    18. nums[i] = nums[minIndex];
    19. nums[minIndex] = num;
    20. }
    1. public static void main(String[] args) {
    2. Integer[] nums = {4, 2, 6, 3, 5, 1};
    3. sort(nums);
    4. sort2(nums);
    5. }

    go实现:

    1. func main() {
    2. sort([]int{4, 2, 6, 3, 5, 1})
    3. }
    4. func sort(nums []int) {
    5. length := len(nums)
    6. for i := 0; i < length; i++ {
    7. minIndex := i
    8. for j := i; j < length; j++ {
    9. if nums[j] < nums[minIndex] {
    10. minIndex = j
    11. }
    12. num := nums[i]
    13. nums[i] = nums[minIndex]
    14. nums[minIndex] = num
    15. }
    16. }
    17. fmt.Println(nums)
    18. }

    项目demo