算法简介
选择排序是一种简单直观的排序算法,无论什么数据进去都是 O(n²) 的时间复杂度。所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间吧。
算法原理如下动图:
图片来源(https://www.runoob.com/w3cnote/selection-sort.html)
- 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置。
- 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
- 重复第二步,直到所有元素均排序完毕。
代码实现:
/** * 选择排序 */ public class SelectSort { public static void SelectSort(int[] arr) { if (arr == null || arr.length <= 1) { return; } for (int i = 0; i < arr.length - 1; i++) { //数组比较次数n-1 int index = i; //保存当前最小元素的位置 for (int j = i + 1; j < arr.length; j++) { //遍历待排序数组元素(i之后的元素) if (arr[index] > arr[j]) { //如果已排序中 较大元素 大于 待排序元素中的 最小元素 则更换元素对应索引 index = j; } } int temp = arr[index]; //置换位置 arr[index] = arr[i]; arr[i] = temp; } } public static void main(String[] args) { int[] arr={2,7,5,3,6,1,4}; SelectSort(arr); System.out.println(Arrays.toString(arr)); } }