0
点赞
收藏
分享

微信扫一扫

经典算法之直接选择排序(SelectionSort)




直接选择排序

  • ​​算法原理​​
  • ​​算法步骤​​
  • ​​动图演示​​
  • ​​java代码实现​​
  • ​​算法分析​​

算法原理

  • 每次从待排序的数据元素中选择最小值或最大值,放在第一位
  • 从剩余的元素中继续寻找最小或最大元素,放在已排序元素的后面
  • 重复以上步骤,直到排序完成

算法步骤

a <===> b :表示交换 a 、b

初始状态 [9 18 38 2 46 8 43 46 5 12 ] 9 <===> 2

第一次:[2 18 38 9 46 8 43 46 5 12 ] 18 <===> 5

第二次:[2 5 38 9 46 8 43 46 18 12 ] 38 <===> 8

第三次:[2 5 8 9 46 38 43 46 18 12 ] 9 <===> 9

第四次:[2 5 8 9 46 38 43 46 18 12 ] 46 <===> 12

第五次:[2 5 8 9 12 38 43 46 18 46 ] 38 <===> 18

第六次:[2 5 8 9 12 18 43 46 38 46 ] 43 <===> 38

第七次:[2 5 8 9 12 18 38 46 43 46 ] 46 <===> 43

第八次: [2 5 8 9 12 18 38 43 46 46] 46<===> 46

第九次: [2 5 8 9 12 18 38 43 46 46] ==> 排序完成

动图演示

经典算法之直接选择排序(SelectionSort)_时间复杂度

java代码实现

public class SelectionSort {
public static void main(String[] args) {
Integer[] arr = {9,18,38,2,46,8,43,46,5,12};
sort(arr);
System.out.println(Arrays.toString(arr));
}

public static void sort(Comparable[] a){
for (int i = 0;i <= a.length - 2;i++){
//定义一个变量,记录最小元素的索引
int minIndex = i;
for (int j = i + 1;j < a.length;j++){
//比minIndex与j两个索引处的值的大小
if (greater(a[minIndex],a[j])){
minIndex = j;
}
}
//交换最小元素的所在索引minIndex处的值与索引值为i的元素的值
swap(a,i,minIndex);
}
}
//比较 v 是否大于 w
public static boolean greater(Comparable v,Comparable w){
return v.compareTo(w) > 0;
}
//数组元素交换位置
private static void swap(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

排序前:{9,18,38,2,46,8,43,46,5,12}
排序后:{2,5,8,9,12,18,38,43,46,46}

算法分析

时间复杂度:

假如被排序的数列中有n个数。遍历一次的时间复杂度是O(n),而我们需要遍历 n -1 次,所以选择排序的时间复杂度是 O(n²)。

空间复杂度: O(1)


举报

相关推荐

0 条评论