【排序算法】简单选择排序

xiaoxiao2021-02-28  96

简单选择排序是一种选择排序。

1.简单选择排序的定义

每趟从待排序的记录中选出关键字最小的记录,顺序放在已排序的记录序列末尾,直到全部排序结束为止。

2.简单选择排序的流程

从待排序序列中,找到关键字最小的元素;

如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换;

从余下的 N - 1 个元素中,找出关键字最小的元素,重复(1)、(2)步,直到排序结束。

实例

注:红色数字是位置发生变化的数值。

3.简单选择排序的代码实现

public class SimpleSelectSort { public void selectionSort(int[] arr) { // 需要遍历获得最小值的次数 // 要注意一点,当要排序 N 个数,已经经过 N-1 次遍历后,已经是有序数列 for (int i = 0; i < arr.length - 1; i++) { int min = i; // 用来保存最小值得索引 // 寻找第i个小的数值 for (int j = i + 1; j < arr.length; j++) { if (arr[min] > arr[j]) { min = j; } } // 若min有变化,就将找到的第i个小的数值与第i个位置上的数值交换 if (min != i) { int temp = arr[min]; arr[min] = arr[i]; arr[i] = temp; } // System.out.format("第 %d 趟:\t", i + 1); // printAll(arr); } } // 打印完整序列 public void printAll(int[] list) { for (int value : list) { System.out.print(value + "\t"); } System.out.println(); } public static void main(String[] args) { // 初始化一个随机序列 final int MAX_SIZE = 10; int[] array = new int[MAX_SIZE]; Random random = new Random(); for (int i = 0; i < MAX_SIZE; i++) { array[i] = random.nextInt(MAX_SIZE); } // 调用选择排序方法 SimpleSelectSort selection = new SimpleSelectSort(); System.out.print("排序前:\t"); selection.printAll(array); // System.out.println(Arrays.toString(array)); selection.selectionSort(array); System.out.print("排序后:\t"); selection.printAll(array); } }

输出结果:

排序前: 3 5 2 9 4 1 7 7 5 3 排序后: 1 2 3 3 4 5 5 7 7 9

4.简单选择排序的特点

运行时间与输入无关

数据移动是最少的

5.算法分析

(1)简单选择排序算法的性能

(2)时间复杂度

简单选择排序的比较次数与序列的初始排序无关。 假设待排序的序列有 N 个元素,则比较次数总是N (N - 1) / 2。

而移动次数与序列的初始排序有关。当序列正序时,移动次数最少,为 0.

当序列反序时,移动次数最多,为3N (N - 1) / 2。

所以,简单排序的时间复杂度为 O(N2)。

(3)空间复杂度

简单选择排序需要占用 1 个临时空间,在交换数值时使用。

(4)稳定性

如果当前锁定元素比后面一个元素大,而后面较小的那个元素又出现在一个与当前锁定元素相等的元素后面,那么交换后位置顺序显然改变了,所以是不稳定的。

本人才疏学浅,若有错,请指出 谢谢!

转载请注明原文地址: https://www.6miu.com/read-68087.html

最新回复(0)