选择排序

1、选择排序

  比如在一个长度为N的无序数组中,在第一趟遍历N个数据,找出其中最小的数值与第一个元素交换,第二趟遍历剩下的N-1个数据,找出其中最小的数值与第二个元素交换......第N-1趟遍历剩下的2个数据,找出其中最小的数值与第N-1个元素交换,至此选择排序完成。

2、代码实现

 1 package com.wcy.sort;
 2 
 3 /**
 4  * 时间:2016年10月19日
 5  * 题目:选择排序
 6  */
 7 public class SelectSortTest {
 8 
 9     /**
10      * 选择排序
11      * @param arr 待排序的数组
12      * @return 排序之后的数组
13      */
14     public static int[] selectSort(int[] arr){
15         for (int i = 0; i < arr.length; i++) {
16             int temp = 0;
17             int num = i; // 存放最小值得下标
18             for (int j = i+1; j < arr.length; j++) {
19                 if (arr[j] < arr[num]) {
20                     num = j;
21                 }
22             }
23             if (num != i) {
24                 temp = arr[i];
25                 arr[i] = arr[num];
26                 arr[num] = temp;
27             }
28         }
29         
30         return arr;
31     }
32     
33     /**
34      * 打印数组函数
35      * @param arr 待打印的数组
36      */
37     public static void showArray(int[] arr){
38         System.out.print("[");
39         for (int i = 0; i < arr.length; i++) {
40             if (i == arr.length-1) {
41                 System.out.print(arr[i]);
42             }else {
43                 System.out.print(arr[i] + ",");
44             }
45         }
46         System.out.println("]");
47     }
48     
49     /**
50      * 用户页面测试
51      * @param args
52      */
53     public static void main(String[] args) {
54         int[] arr = {49,38,65,97,76,13,27,49};
55         int[] arrResult = selectSort(arr);
56         showArray(arrResult);
57     }
58 }
原文地址:https://www.cnblogs.com/wangchaoyuan/p/5979032.html