描述:
每次遍历找到一个最大/最小的元素,与当前需要确定的位置进行交换
代码实现:
let a = [9, 1, 4, 3, 2, 5, 6, 8, 7];
function SelectionSort(array) {
let minIndex , temp;
for (let i = 0; i < array.length - 1; i++) {
minIndex = i;
for (let j = i + 1; j < array.length; j++) {
if(array[j] < array[minIndex]){
minIndex = j;
}
}
temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
SelectionSort(a);
时间复杂度:
- 最好:O(n²)
- 最坏:O(n²)
- 平均:O(n²)