选择排序——java实现

选择排序核心思想是通过每一次遍历选择最小元素:

for: i from 0~n-1 {

  for j from i+1~n-1

        选出最小元素a[min]

  将选出的最小元素a[min]与a[i]交换位置

}

 1 package 排序;
 2 
 3 import java.util.Arrays;
 4 import edu.princeton.cs.algs4.In;
 5 import edu.princeton.cs.algs4.StdOut;
 6 /**
 7  * 特点:
 8  * 1.运行时间与输入无关。为了找出最小的元素而扫描一遍数组,并不能为下一遍扫描提供什么信息
 9  *     一个已经有序的数组或是主键全部相等的数组或元素随机排列的数组所用的排序时间一样长
10  * 2.数据移动最少。每次交换都会改变两个数组元素的值,交换次数与数组大小线性相关
11  * @author evasean www.cnblogs.com/evasean/
12  *
13  */
14 @SuppressWarnings("rawtypes")
15 public class Selection选择排序 {
16     public static void sort(Comparable[] a){
17         int n = a.length;
18         for(int i=0; i<n; i++){
19             int min = i;
20             for(int j=i+1; j<n; j++){
21                 if(less(a[j],a[min])) min = j;
22             }
23             exch(a,i,min);
24         }
25     }
26     @SuppressWarnings("unchecked")
27     private static boolean less(Comparable v, Comparable w){
28         return v.compareTo(w) < 0;
29     }
30     private static void exch(Comparable[] a, int i, int j){
31         Comparable t = a[i];
32         a[i] = a[j];
33         a[j] = t;
34     }
35     private static void show(Comparable[] a){
36         for(int i=0; i<a.length; i++) StdOut.print(a[i] + " ");
37         StdOut.println();
38     }
39     public static boolean isSorted(Comparable[] a){
40         for(int i = 1; i < a.length; i++){
41             if(less(a[i],a[i-1])) return false;
42         }
43         return true;
44     }
45     public static void main(String[] args){
46         String[] a = new In().readAllStrings();
47         StdOut.println(Arrays.toString(a));
48         sort(a);
49         assert isSorted(a);
50         show(a);
51     }
52 }
原文地址:https://www.cnblogs.com/evasean/p/7232806.html