排序之 -- 直接选择排序

示意:

初始数组资源 【63        4        24        1        3        15】

第一趟排序后 【15        4        24        1        3】     63
第二趟排序后 【15        4        1          3】    24       63
第三趟排序后 【4          1        3】      15      24       63
第四趟排序后 【1          3】     4         15      24       63
第五趟排序后 【1】       3        4         15      24       63

实例:

 1 /**
 2  * 直接选择排序算法实例
 3  * 
 4  * @author Li Zhong Wei
 5  */
 6 public class SelectSort {
 7     public static void main(String[] args) {
 8         // 创建一个数组,这个数组元素是乱序的
 9         int[] array = { 63, 4, 24, 1, 3, 15 };
10         // 创建直接排序类的对象
11         SelectSort sorter = new SelectSort();
12         // 调用排序对象的方法将数组排序
13         sorter.sort(array);
14     }
15     
16     /**
17      *直接选择排序法
18      * 
19      * @param array
20      *            要排序的数组
21      */
22     public void sort(int[] array) {
23         int index;
24         for (int i = 1; i < array.length; i++) {
25             index = 0;
26             for (int j = 1; j <= array.length - i; j++) {
27                 if (array[j] > array[index]) {
28                     index = j;
29                 }
30             }
31             // 交换在位置array.length-i和index(最大值)两个数
32             int temp = array[array.length - i];// 把第一个元素值保持到临时变量中
33             array[array.length - i] = array[index];// 把第二个元素值保存到第一个元素单元中
34             array[index] = temp;// 把临时变量也就是第一个元素原值保持到第二个元素中
35         }
36         showArray(array);// 输出直接选择排序后的数组值
37     }
38     
39     /**
40      * 显示数组所有元素
41      * 
42      * @param array
43      *            要显示的数组
44      */
45     public void showArray(int[] array) {
46         for (int i : array) {// foreach格式遍历数组
47             System.out.print(" >" + i);// 输出每个数组元素值
48         }
49         System.out.println();
50     }
51 }
原文地址:https://www.cnblogs.com/zhuyongzhe/p/7046251.html