简单选择排序是一种选择排序。
选择排序:每趟从待排序的记录中选出关键字最小的记录,顺序放在已排序的记录序列末尾,直到全部排序结束为止。
(1)从待排序序列中,找到关键字最小的元素;
(2)如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换;
(3)从余下的 N - 1 个元素中,找出关键字最小的元素,重复(1)、(2)步,直到排序结束。
如图所示,每趟排序中,将当前第 i 小的元素放在位置 i 上。
核心代码
public void selectionSort( int[] list) { // 需要遍历获得最小值的次数 // 要注意一点,当要排序 N 个数,已经经过 N-1 次遍历后,已经是有序数列 for ( int i = 0; i < list.length - 1; i++) { int temp = 0; int index = i; // 用来保存最小值得索引 // 寻找第i个小的数值 for ( int j = i + 1; j < list.length; j++) { if (list[index] > list[j]) { index = j; } } // 将找到的第i个小的数值放在第i个位置上 temp = list[index]; list[index] = list[i]; list[i] = temp; System.out.format("第 %d 趟:\t", i + 1); printAll(list); } }
排序类别
排序方法
时间复杂度
空间复杂度
稳定性
复杂性
平均情况
最坏情况
最好情况
选择排序
简单选择排序
O(N2)
O(N2)
O(N2)
O(1)
不稳定
简单
简单选择排序的比较次数与序列的初始排序无关。 假设待排序的序列有 N 个元素,则比较次数总是N (N - 1) / 2。
而移动次数与序列的初始排序有关。当序列正序时,移动次数最少,为 0.
当序列反序时,移动次数最多,为3N (N - 1) / 2。
所以,综合以上,简单排序的时间复杂度为 O(N2)。
简单选择排序需要占用 1 个临时空间,在交换数值时使用。
代码实现
1 package notes.javase.algorithm.sort; 2 3 import java.util.Random; 4 5 public class SelectionSort { 6 7 public void selectionSort( int[] list) { 8 // 需要遍历获得最小值的次数 9 // 要注意一点,当要排序 N 个数,已经经过 N-1 次遍历后,已经是有序数列 10 for ( int i = 0; i < list.length - 1; i++) { 11 int temp = 0; 12 int index = i; // 用来保存最小值得索引 13 14 // 寻找第i个小的数值 15 for ( int j = i + 1; j < list.length; j++) { 16 if (list[index] > list[j]) { 17 index = j; 18 } 19 } 20 21 // 将找到的第i个小的数值放在第i个位置上 22 temp = list[index]; 23 list[index] = list[i]; 24 list[i] = temp; 25 26 System.out.format("第 %d 趟:\t", i + 1); 27 printAll(list); 28 } 29 } 30 31 // 打印完整序列 32 public void printAll( int[] list) { 33 for ( int value : list) { 34 System.out.print(value + "\t"); 35 } 36 System.out.println(); 37 } 38 39 public static void main(String[] args) { 40 // 初始化一个随机序列 41 final int MAX_SIZE = 10; 42 int[] array = new int[MAX_SIZE]; 43 Random random = new Random(); 44 for ( int i = 0; i < MAX_SIZE; i++) { 45 array[i] = random.nextInt(MAX_SIZE); 46 } 47 48 // 调用冒泡排序方法 49 SelectionSort selection = new SelectionSort(); 50 System.out.print("排序前:\t"); 51 selection.printAll(array); 52 selection.selectionSort(array); 53 System.out.print("排序后:\t"); 54 selection.printAll(array); 55 } 56 57 } View Code运行结果
排序前: 3 5 2 8 1 2 0 8 4 1 第 1 趟: 0 5 2 8 1 2 3 8 4 1 第 2 趟: 0 1 2 8 5 2 3 8 4 1 第 3 趟: 0 1 1 8 5 2 3 8 4 2 第 4 趟: 0 1 1 2 5 8 3 8 4 2 第 5 趟: 0 1 1 2 2 8 3 8 4 5 第 6 趟: 0 1 1 2 2 3 8 8 4 5 第 7 趟: 0 1 1 2 2 3 4 8 8 5 第 8 趟: 0 1 1 2 2 3 4 5 8 8 第 9 趟: 0 1 1 2 2 3 4 5 8 8 排序后: 0 1 1 2 2 3 4 5 8 8
《数据结构习题与解析》(B级第3版)
欢迎阅读 程序员的内功——算法 系列