算法描述
- 将数组分为两个子集,排序的和未排序的,每一轮从未排序的子集中选出最小的元素,放入排序子集
- 重复以上步骤,直到整个数组有序
优化点:
- 为减少交换次数,每一轮可以先找最小的索引,在每轮最后再交换元素
与冒泡排序比较
- 二者平均时间复杂度都是 O ( n 2 ) O(n^2) O(n2)
- 选择排序一般要快于冒泡,因为其交换次数少
- 但如果集合有序度高,冒泡优于选择
- 冒泡属于稳定排序算法,而选择属于不稳定排序
- 稳定排序指,按对象中不同字段进行多次排序,不会打乱同值元素的顺序
- 不稳定排序则反之
/**
* @author 程文旭呀
* @create 2022/8/6
*/
package com.unit.sort;
import java.util.Arrays;
/**
*ClassName:SelectionSort
*Package:com.unit.sort
*Description:选择排序(取最小值,放最前面), 时间复杂度O(n^2)
*@author 程文旭
@create -08-06 16:28
*/
public class SelectionSort {
public static void main(String[] args) {
int[] a = {18,23, 19, 9, 23, 15};
selection(a);
}
//选择排序
public static void selection(int[] arr){
//经历多少次选择
for (int i = 0; i < arr.length -1; i++) {
// i 代表每轮选择最小元素要交换到的目标索引
int s = i; // 代表最小元素的索引
for (int j = s+1; j < arr.length; j++) {//循环结束,可以拿到最小值的索引
if(arr[s]>arr[j]){
s = j;//把最小元素索引赋值给变量
}
}
if(s!=i){
swap(arr,s,i);
}
System.out.println(Arrays.toString(arr));
}
}
//数组交换位置
public static void swap(int[] a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
扑克牌排序
稳定排序与不稳定排序
System.out.println("=================不稳定================");
Card[] cards = getStaticCards();
System.out.println(Arrays.toString(cards));
selection(cards, Comparator.comparingInt((Card a) -> a.sharpOrder).reversed());
System.out.println(Arrays.toString(cards));
selection(cards, Comparator.comparingInt((Card a) -> a.numberOrder).reversed());
System.out.println(Arrays.toString(cards));
System.out.println("=================稳定=================");
cards = getStaticCards();
System.out.println(Arrays.toString(cards));
bubble(cards, Comparator.comparingInt((Card a) -> a.sharpOrder).reversed());
System.out.println(Arrays.toString(cards));
bubble(cards, Comparator.comparingInt((Card a) -> a.numberOrder).reversed());
System.out.println(Arrays.toString(cards));
都是先按照花色排序(♠♥♣♦),再按照数字排序(AKQJ…)
- 不稳定排序算法按数字排序时,会打乱原本同值的花色顺序
原来 ♠2 在前 ♥2 在后,按数字再排后,他俩的位置变了[[♠7], [♠2], [♠4], [♠5], [♥2], [♥5]] [[♠7], [♠5], [♥5], [♠4], [♥2], [♠2]]
- 稳定排序算法按数字排序时,会保留原本同值的花色顺序,如下所示 ♠2 与 ♥2 的相对位置不变
[[♠7], [♠2], [♠4], [♠5], [♥2], [♥5]] [[♠7], [♠5], [♥5], [♠4], [♠2], [♥2]]