选择排序——Java实现

一、排序思想

选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是:

  1. 从待排序列中选出最小(或最大)的一个元素,记录其下标(数组)的位置;
  2. 将记录的下标值与待排序列的第一个元素进行交换;
  3. 以此类推,直到全部待排序列的元素排完。

二、图解

SelectionSort

三、代码实现

 1 public class SelectionSort {
 2     public static void main(String[] args) {
 3         int[] arr = {43, 21, 65, 23, 65, 33, 21, 12, 43, 54};
 4 
 5         selectionSort(arr);
 6 
 7         for (int i : arr) {
 8             System.out.print(i + "\t");
 9         }
10     }
11 
12     private static void selectionSort(int[] arr) {
13         for (int i = 0; i < arr.length - 1; i++) {
14             int minIndex = i;
15             for (int j = i + 1; j < arr.length; j++) {
16                 if (arr[minIndex] > arr[j]) {
17                     minIndex = j;
18                 }
19             }
20             if (minIndex != i) {
21                 int temp = arr[i];
22                 arr[i] = arr[minIndex];
23                 arr[minIndex] = temp;
24             }
25         }
26     }
27 }

 

posted @ 2019-03-22 22:36  Lvan灬  阅读(3568)  评论(0编辑  收藏  举报