<p>源数据:[10, -1, 20, 30, 0, 40, 1, 100]</p>
<p>排序:<span id="j-arr"></span></p>
// 找出数组中最小的数字
function findSmallest (arr) {
let minValue = arr[0]
let minIndex = 0
for (let i in arr) {
let item = arr[i]
if (item >= minValue) { continue }
minIndex = i
minValue = item
}
return minIndex
}
// 对数字进行排序
function selectionSort (arr) {
let len = arr.length
let newArr = []
for (let i = 0; i < len; i++) {
let minIndex = findSmallest(arr)
newArr.push(arr[minIndex])
arr.splice(minIndex, 1)
}
return newArr
}
document.getElementById('j-arr').innerText = selectionSort([10, -1, 20, 30, 0, 40, 1, 100])
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.