选择排序是一种简单直观的排序算法,无论什么数据进去都是 O(n²)
的时间复杂度。所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。
算法步骤
-
首先在未排序序列中找到最小(大)元素,存放到排序序列的起始(末尾)位置。
-
再从剩余未排序元素中继续寻找最小(大)元素,然后放到未排序序列的起始(末尾)位置。
-
重复第二步,直到所有元素均排序完毕。
动图演示
代码演示
/**选择排序*/
public class SelectionSort {
public void sort(Comparable[] arr){
for(int i=0;i<arr.length-1;i++){
int minIndex = i;
for(int j=i+1;j<arr.length;j++){
if (greater(arr[minIndex],arr[j])){
// this.swap(arr,i,j);
minIndex = j;
}
}
this.swap(arr,i,minIndex);
}
}
/**比较两者的大小*/
private Boolean greater(Comparable a, Comparable b){
int i = a.compareTo(b);
if (i>=0)
return true;
return false;
}
/**交换位置*/
private void swap(Comparable[] arr,int i , int j){
Comparable temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public class SelectionSortTest {
public static void main(String[] args) {
Integer[] arr = {5,6,3,8,1,2,9,4,1};
SelectionSort selectionSort = new SelectionSort();
selectionSort.sort(arr);
System.out.println(Arrays.toString(arr)); //[1, 1, 2, 3, 4, 5, 6, 8, 9]
}
}
算法分析
选择排序使用了双层for循环,其中外层循环完成了数据交换,内层循环完成了数据比较,所以我们分别统计数据交换和数据比较的次数:
(n-1)+(n-2)+…+2+1 = n(n-1)/2
数据交换次数:
3*(n-1)
时间复杂度:
n(n-1)/2+3*(n-1)
根据大O推到算法,保留最高阶项,时间复杂度为O(n^2)
。