选择排序算法是一种原址比较排序算法。选择排序算法的思路是:找到数据结构中的最小值并将其放置在第一位,接着找到第二小的值并将其放在第二位,以此类推。
Array.prototype.selectionSort = function() {
let indexMin
for (let i = 0; i < this.length - 1; i++){
indexMin = i
for (var j = i; j < this.length; j++){
if(this[indexMin] > this[j]) {
indexMin = j
}
}
if (i !== indexMin){
let aux = this[i]
this[i] = this[indexMin]
this[indexMin] = aux
}
}
return this
}
function selectionSort(arr) {
let len = arr.length;
var minIndex, temp;
for (let i = 0; i < len - 1; i++) {
minIndex = i;
for (let j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}