选择排序

121 阅读1分钟

什么是选择排序(selectSort)?

选择排序就是在一个排列中划分为有序区和无序区,有序区在左边,无序区在右边。首先在无序区中找到最小元素,存放到有序区的起始位置,然后再从剩余的无序区中继续寻找最小元素,然后放到有序区的末尾。以此类推,直到无序区没有元素可排列。

动画展示

1646382718837-bd8d0029-4a9e-4751-94ef-680162abb68f.gif

算法步骤

  1. 首先在数组中查找出最小的元素
  2. 把当前最小元素放在数组的第一位
  3. 继续查找数组中最小的元素(不包含刚才找过的最小元素)
  4. 把当前最小元素放在数组的第二位
  5. 以此类推,执行 n - 1 轮
  6. 完成排序

代码实现

package array;

import java.util.Arrays;

public class SelectSort {

    public static void main(String[] args) {
        int[] arrs = { 8, 6, 1, 7, 2, 5, 4, 12, 9 };
        int[] newArrs = SelectSort.selectSort(arrs);
        System.out.println(Arrays.toString(newArrs));
    }

    // 选择排序
    // 时间复杂度:O(n^2)

    public static int[] selectSort(int[] nums) {

        // 判断是否是空和只有自己,如果是就返回自己
        if (nums == null || nums.length == 1) {
            return nums;
        }

        // 循环遍历数组
        for (int i = 0; i < nums.length; i++) {
            
            int index = i;

            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] < nums[index]) {
                    index = j;
                }
            }

            if (index != i) {
                int temp = nums[i];
                nums[i] = nums[index];
                nums[index] = temp;
            }

        }
        return nums;
    }

}