選擇排序——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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM