归纳公式
转公式为代码
https://jsbin.com/jayojekabe/2/edit?js,console
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];const _sortSelect = (a, start) => {if (start >= a.length - 1) return a;let min = a[start];let minIndex = start;for(let i = start + 1; i < a.length; i++) {if (a[i] < min) {min = a[i];minIndex = i;}}if (minIndex !== start) {swap(a, start, minIndex);}return _sortSelect(a, start + 1);}const sortSelect = (a) => _sortSelect(a, 0);console.log('------------', sortSelect([2, 1, 3, 1, 4]))console.log('--------', sortSelect([1,2,9,4,10,20,12]))// // [1, 2, 4, 9, 10, 12, 20]console.log('--------', sortSelect([11,2,39,24,1,2,9]))// // [1, 2, 2, 9, 11, 24, 39]console.log('--------', sortSelect([]))// // []console.log('--------', sortSelect([1,1,1,1,1]))const sortSelect2 = (a) => {for(let i = 0; i < a.length; i++) {let min = a[i];let minIndex = i;for(let j = i + 1; j < a.length; j ++) {if (a[j] < min) {min = a[j];minIndex = j;}}swap(a, i, minIndex);}return a;}console.log('------------', sortSelect2([2, 1, 3, 1, 4]))console.log('--------', sortSelect2([1,2,9,4,10,20,12]))// // // [1, 2, 4, 9, 10, 12, 20]console.log('--------', sortSelect2([11,2,39,24,1,2,9]))// // // [1, 2, 2, 9, 11, 24, 39]console.log('--------', sortSelect2([]))// // // []console.log('--------', sortSelect2([1,1,1,1,1]))
