求最小值
let min = (numbers) => {
if(numbers.length > 2){
return min([numbers[0],min(numbers.slice(1))])
}else{
return Math.min.apply(null,numbers)
}
}
任意长度的数组排序
总结:每次找到最小的数放在前面,然后对后面的数做同样的事情。
代码实现 从小到大
let minIndex = (numbers) => numbers.indexOf(min(numbers))
let min = (numbers) => {
if(numbers.length > 2){
return min([numbers[0],min(numbers.slice(1))])
}else{
return Math.min.apply(null,numbers)
}
}
var sort = (numbers) => {
if(numbers.length > 2){
let index = minIndex(numbers)
let min = numbers[index]
console.log(`min: ${min}`)
numbers.splice(index,1)
return [min].concat(sort(numbers))
}else{
return numbers[0]<numbers[1] ? numbers : numbers.reverse()
}
}
代入法理解:
sort[12,5,8,7,9]
=[5]+(sort(12,8,7,9))
=[5]+([7]+(sort(12,8,9)))
=[5]+([7]+([8]+(sort(12,9))))
=[5]+([7]+([8]+([9,12])))
=[5]+([7]+([8,9,12]))
=[5]+([7,8,9,12])
=[5,7,8,9,12]