Selection Sort
原理是從待排序的數列中,找出最小的數並放到排序的第一個位置,然後再從待排序的數列中,找出次小的數並放到排序的第二個位置,以此類推。

選擇排序演算法的運作如下:

  • 從頭開始,每次找出最小的元素
  • 依序擺放至正確位置。
Values:
[
18,
25,
22,
18,
11,
27,
0,
24,
3,
5,
19,
5,
29,
21,
4,
7,
4,
13,
4,
21,
]
Implementation

              function selectionSort (arr) {
                const n = arr.length
                
                for (let i = 0; i < n - 1; i++) {
                  let minIndex = i
                  for (let j = i + 1; j < n; j++) {
                    if (arr[j] < arr[minIndex]) {
                      minIndex = j
                    }
                  }
                  if (minIndex !== i) {
                    let tempValue = arr[i]
                    arr[i] = arr[minIndex]
                    arr[minIndex] = tempValue
                  }
                }
              }
              
Copyright © 2020-2023 | Design by Waiting7777