<<<<<<<<<<<<--------->>>>>>>>>>>>>>>>
選擇排序是一種簡單直觀的排序演算法,而且它不會占用額外的記憶體空間,
原理:遍歷元素找到一個最小或最大的元素,把它放在第一個位置,然后再從剩余的元素中找到最小或最大的元素,把它放在第二個位置,依次下去,直到完成排序,
時間復雜度為O(n2)
思路:
給定一個陣列 s[]
第一趟排序,在待排序的n個元素中選出最小的一個,將它與s[1]交換;
第二趟排序,在剩下的待排序元素s[2]~s[n]中選出最小的一個資料,將它與s[2]交換;
...
以此類推
第n-1趟排序,在待排序的s[n-1]~s[n]中選出最小的資料,將它與s[n-1]交換
排序完成,
動圖演示效果:

Java代碼實作:
1 public class SelectionSort { 2 public static void main(String[] args) { 3 int[] arr = new int[] { 5, 3, 6, 2, 10, 2, 1 }; 4 selectSort(arr); 5 for (int i = 0; i < arr.length; i++) { 6 System.out.print(arr[i] + " "); 7 } 8 } 9 public static void selectSort(int[] arr) { 10 for (int i = 0; i < arr.length - 1; i++) { 11 int minIndex = i; // 用來記錄最小值的索引位置,默認值為i 12 for (int j = i ; j < arr.length; j++) { 13 if (arr[j] < arr[minIndex]) { 14 minIndex = j; // 遍歷 i~length 的值,找到其中最小值的位置 15 } 16 } 17 if (i != minIndex) { // 交換當前索引 i 和最小值索引 minIndex 兩處的值 18 int temp = arr[i]; 19 arr[i] = arr[minIndex]; 20 arr[minIndex] = temp; 21 } // 執行完一次回圈,當前索引 i 處的值為最小值,直到回圈結束即可完成排序 22 } 23 } 24 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/139969.html
標籤:其他
上一篇:C語言遞回之二叉樹的最大深度
