选择性排序

名词解释:——来自百度百科

  选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法。

 1 public class SelectionSort {
 2 
 3     public static void main(String[] args) {
 4         int[] arr = {100, 30, 70, 20, 80, 60, 40, 50, 90, 10};
 5         arr = selectionSort(arr);
 6         System.out.println(Arrays.toString(arr));
 7     }
 8 
 9     private static int[] selectionSort(int[] arr){
10         int minIndex = 0;
11         int temp = 0;
12         for (int i = 0; i < arr.length; i++) {
13             // 无序区数组的最小索引
14             minIndex = i;
15             for (int j = i + 1; j < arr.length; j++) {
16                 // 无序区数组中找到最小元素,并保存其索引
17                 if (arr[j] < arr[minIndex]) {
18                     minIndex = j;
19                 }
20             }
21             // 将无序区中找出的最小元素放到本次循环的前端
22             temp = arr[i];
23             arr[i] = arr[minIndex];
24             arr[minIndex] = temp;
25         }
26         return arr;
27     }
28 }

 

posted @ 2018-12-07 00:18  Java梦工厂  阅读(269)  评论(0编辑  收藏  举报