选择排序
可以选择最小的排到最前面,然后和剩余的元素拼接成新的数组
var testArr = [12, 72, 34, 95, 43, 5, 24, 67, 6, 8, 79,2, 55, 33, 24, 3];
// 获取当前最小的
const getMin = (numbers) => {
let min = numbers[0];
let minIndex = 0;
for (let i in numbers) {
if (numbers[i] < min) {
min = numbers[i];
minIndex = Number(i);
}
}
return {min, minIndex};
}
//排它
const sortArr = (numArr) => {
const theMin = getMin(numArr).min;
const theIndex = getMin(numArr).minIndex;
// console.log(numArr, theMin, theIndex)
if (numArr.length > 2) {
numArr.splice(theIndex, 1);
return [theMin].concat(sortArr(numArr))
} else {
return numArr[0] < numArr[1] ? numArr : numArr.reverse();
}
}
console.log('排序结果:',sortArr(testArr))
网友评论