1.选择排序原理
在第 i 趟的记录序列中选取第 i 小的记录作为有序序列的第 i 个记录。
基于此思想的算法主要有简单选择排序、树型选择排序和堆排序。
2. 简单选择排序
给定数组:int[ ] arr={n1,n2,n3, ...}( 共 n 个数 );第1趟排序,在待排序数据arr[0]~arr[n-1]中选出最小的数据,将它与arrr[0]交换;第2趟,在待排序数据arr[1]~arr[n-1]中选出最小的数据,将它与r[1]交换;以此类推,第 i 趟在待排序数据arr[ i-1 ]~arr[n-1]中选出最小的数据,将它与r[i-1]交换,直到全部排序完成。
package com.zth;
import java.util.Arrays;
public class SelectionSort {
public static void main(String[] args){
int[] array = {3,2,5,8,4,7,6,9};
selectionSort(array);
System.out.println(Arrays.toString(array));
}
private static void selectionSort(int[] array) {
// 合法性检查
if(array == null && array.length==0){
return;
}
int min;
for (int i = 0; i < array.length-1; i++) {
min = array[i];
for (int j = i+1; j <array.length ; j++) {
if(min > array[j]){
min = min ^ array[j];
array[j] = min ^ array[j];
min = min ^ array[j];
}
}
array[i] = min;
}
}
}
2.1 性能
时间复杂度 | 空间复杂度 | 稳定性 | 复杂性 | ||
最坏情况 | 最好情况 | 平均情况 | |||
o(n^2) | o(n^2) | o(n^2) | o(1) | 不稳定 | 简单 |
3. 树形选择排序
树形选择排序也叫锦标赛排序。
先把待排序的 n 个元素两两进行比较,取出较小的。然后在 个较小者中再两两一组进行比较,取出较小的,重复上述步骤,直到取出最小元素。 经过 n 趟比较,可以完成整个排序。
整个树形选择排序用一棵有 n 个叶子节点的完全二叉树来完成。每一趟选出的最小值就是该棵树的根节点。在选出最小元素后,将这个元素对应的叶子节点的值置为 ∞,然后把不为 ∞ 的兄弟节点移到父节点的位置。重复执行,知道输出所有的值。
【例】
(图片来源:https://www.jianshu.com/p/b20ed599ac07)
package com.zth.sort;
import java.util.Arrays;
public class TreeSelectSort {
public static void main(String[] args){
int[] array = {1,8,7,4,2,3,5,6};
treeSelectSort(array);
System.out.println(Arrays.toString(array));
}
public static void treeSelectSort(int[] array){
int treeSize = array.length*2 - 1; //完全二叉树的节点数
int index = 0; // 待排序数组的元素索引指针
int[] tree = new int[treeSize]; // 临时存储树
/**
* 从后往前填充树,索引从 0 开始
*/
// 填充叶子节点
for (int i = array.length-1,j = 0; i>=0;i--,j++){
tree[treeSize-1-j] = array[i];
}
// 填充非叶子节点(比较叶子节点,填入到父节点)
for (int i = treeSize-1; i >0; i -=2) {
tree[(i-1)/2] = (tree[i]-tree[i-1])>0 ? tree[i-1] : tree[i];
}
// 移走最小值
int minIndex;
while (index < array.length){
int min = tree[0];
array[index++] = min ;
//找到最小值的索引
minIndex = treeSize-1;
while(tree[minIndex]-min !=0){
minIndex--;
}
// 将最小值设为最大值
tree[minIndex] = Integer.MAX_VALUE;
//找到该节点的兄弟节点
while (minIndex >0){ // minIndex >0 则还有父节点
if (minIndex %2 == 0){ // 偶数则为右节点,和左节点比较,取最小值
tree[(minIndex-1)/2] = (tree[minIndex]-tree[minIndex-1])>0 ? tree[minIndex-1] : tree[minIndex];
minIndex = (minIndex - 1)/2; //设置为父节点的索引,继续向上比对
}else{ // 奇数则为左节点
tree[(minIndex)/2] = (tree[minIndex]-tree[minIndex+1])>0 ? tree[minIndex+1] : tree[minIndex];
minIndex = minIndex /2; //设置为父节点的索引,继续向上比对
}
}
}
}
}
由于含有 n 个叶子结点的完全二叉树的深度为 +1,则在树形选择排序中,除了最小关键字以外,每选择一个次小关键字仅需进行 次比较,因此,它的时间复杂度为O(n logn)。
和简单选择排序相比,比较次数减少了,但增加了 n-1 个辅助空间。
4. 堆排序
排序算法 | 时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 稳定性 |
简单选择排序 | o(n^2) | o(n^2) | o(n^2) | 0(1) | 不稳定 |
树形选择排序 | o(n log n) | o(n log n) | o(n log n) | 0(n) | 稳定 |
堆排序 | o(n log n) | o(n log n) | o(n log n) | 0(1) | 不稳定 |