算法 - 选择排序

选择排序算法:首先在未排序序列中找到最小(最大)元素,存放到排序序列的其实位置,然后,再从剩余未排序元素中继续寻找最小(最大)元素,然后放到已排序序列的末尾。以此类推,知道所有元素均排序完毕。

代码实现如下:

 

 1 package com.yunstars.selectsort;
 2 
 3 /**
 4  * Created by zhangshengjian on 2016/7/15.
 5  * 选择排序算法
 6  */
 7 public class Selection {
 8     public static void sort(Comparable<Integer>[] a) {
 9         if (isSorted(a)) return;
10         int N = a.length;
11         for (int i = 0; i < N; i++) {
12             for (int j = i + 1; j < N; j++) {
13                 if (less(a[j], a[i])) {
14                     swap(a, i, j);
15                 }
16             }
17         }
18     }
19 
20     /**
21      * 比较两个值的大小
22      * @param v 第一个值
23      * @param w 第二个值
24      * @return 如果第一个值大于第二个值,则返回false 反之
25      */
26     public static boolean less(Comparable<Integer> v, Comparable<Integer> w) {
27         return v.compareTo((Integer) w) < 0;
28     }
29 
30     /**
31      * 调换数组中两个数值的位置
32      * @param a 数组
33      * @param i 第一个数值
34      * @param j 第二个数值
35      */
36     public static void swap(Comparable<Integer>[] a, int i, int j) {
37         if (a[i].equals(a[j])) return;
38         Comparable<Integer> t = a[i];
39         a[i] = a[j];
40         a[j] = t;
41     }
42 
43     /**
44      * 判断一个数组中,前一个值和后一个值的大小(即数组中的数值大小是否已经按大小顺序排好)
45      * @param a 数组
46      * @return 如果数组中所有的前一个值都大于后一个值(即后一个值都小于前一个值),那么返回false 反之
47      */
48     public static boolean isSorted(Comparable<Integer>[] a) {
49         for (int i = 1; i < a.length; i++) {
50             if (less(a[i], a[i - 1])) return false;
51         }
52         return true;
53     }
54 
55     public static void main(String[] args) {
56         Integer[] numbers = {0,1,10,11,2,3,4,5};
57         sort(numbers);
58         for(Integer s:numbers) {
59             System.out.println(s.toString());
60         }
61     }
62 
63 }

 

欢迎各位观众老爷们打赏宝宝,宝宝会继续努力!(扫描支付宝二维码,打赏宝宝,一切皆因为有你的支持!么么哒)

 

posted @ 2016-07-21 10:21  坚持到放弃  阅读(237)  评论(0编辑  收藏  举报