选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
选择排序的主要优点与数据移动有关。如果某个元素位于正确的最终位置上,则它不会被移动。选择排序每次交换一对元素,它们当中至少有一个将被移到其最终位置上,因此对n个元素的表进行排序总共进行至多n-1次交换。在所有的完全依靠交换去移动元素的排序方法中,选择排序属于非常好的一种。
最差时间复杂度 | О(n²) |
---|---|
最优时间复杂度 | О(n²) |
平均时间复杂度 | О(n²) |
最差空间复杂度 | О(n) total, O(1) auxiliary |
代码实现:
- <span style="font-family:Microsoft YaHei;font-size:12px;">package com.baobaotao.test;
- /**
- * 排序研究
- * @author benjamin(吴海旭)
- * @email benjaminwhx@sina.com / 449261417@qq.com
- *
- */
- public class Sort {
- /**
- * 选择排序
- * @param array 数组
- */
- public static void selectSort(int[] array) {
- int length = array.length ;
- int index = 0 ;
- for(int i=0;i<length-1;i++) {
- index = i ;
- for(int j=i+1;j<length;j++) {
- if(array[j] < array[index]) {
- index = j ;
- }
- }
- swap(array, i, index) ;
- printArr(array) ;
- }
- }
- /**
- * 按从小到大的顺序交换数组
- * @param a 传入的数组
- * @param b 传入的要交换的数b
- * @param c 传入的要交换的数c
- */
- public static void swap(int[] a, int b, int c) {
- if(b == c) return ;
- int temp = a[b] ;
- a[b] = a[c] ;
- a[c] = temp ;
- }
- /**
- * 打印数组
- * @param array
- */
- public static void printArr(int[] array) {
- for(int c : array) {
- System.out.print(c + " ");
- }
- System.out.println();
- }
- public static void main(String[] args) {
- int[] number={11,95,45,15,78,84,51,24,12} ;
- selectSort(number) ;
- }
- }
- </span>
输出:
- <span style="font-family:Microsoft YaHei;font-size:12px;">11 95 45 15 78 84 51 24 12
- 11 12 45 15 78 84 51 24 95
- 11 12 15 45 78 84 51 24 95
- 11 12 15 24 78 84 51 45 95
- 11 12 15 24 45 84 51 78 95
- 11 12 15 24 45 51 84 78 95
- 11 12 15 24 45 51 78 84 95
- 11 12 15 24 45 51 78 84 95 </span>
转载请标注:http://blog.csdn.net/benjamin_whx/article/details/42488715