排序算法(二):选择排序
一、排序原理
1. 每一次遍历的过程中,都假定第一个索引处的值都是最小值,和其他索引处的值依次进行比较,如果当前索引处的值大于其他某处索引处的值,则假定某个索引处的值为最小值,最后可以找到最小值所在的索引。
2. 交换第一个索引和最小值所在索引处的值。
二、代码实现
import java.util.Arrays; /** * 选择排序 */ public class SelectSort { public static void main(String[] args) { Integer[] arr = {4, 5, 3, 9, 2, 1}; sort(arr); System.out.println(Arrays.asList(arr).toString()); } public static void sort(Comparable[] a) { for (int i = 0; i <= a.length - 2; i++) { // 定义一个变量,记录最小元素所在的索引,默认为参与选择排序的第一个元素所在的位置 int minIndex = i; for (int j = i; j < a.length; j++) { // 需要比较最小索引minIndex处的值和j索引处的值 if (greater(a[minIndex], a[j])) { minIndex = j; } } // 交换最小元素所在索引minIndex处的值和j索引处的值 exch(a, i, minIndex); } } private static boolean greater(Comparable i, Comparable j) { return i.compareTo(j) > 0; } public static void exch(Comparable[] a, int i, int j) { Comparable temp = a[i]; a[i] = a[j]; a[j] = temp; } }
输出结果:
[1, 2, 3, 4, 5, 9]
三、选择排序时间复杂度分析
按照大O推导法则,可得知选择排序的时间复杂度为O(n^2)。
适用场景:适用元素较少的排序场景。