1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| const arr = [7, 2, 3, 2, 6, 9 ,0 ,11,11]
let getMin = function getMin(arr) { let minValue = 0, minIndex = 0 arr.forEach((item, index) => { if (index === 0) { minValue = item return } if (item <= minValue) { minValue = item minIndex = index } }) return { minValue, minIndex } }
let getMax = function getMax(arr) { let maxValue = 0, maxIndex = 0 arr.forEach((item, index) => { if (index === 0) { maxValue = item return } if (item > maxValue) { maxValue = item maxIndex = index } }) console.log('最大值', maxValue, maxIndex)
return { maxValue, maxIndex } }
let filterMinAndMax = function filterMinAndMax(minIndex, maxIndex, arr) { let newArr = [] arr.forEach((item, index) => { if (index === minIndex || index === maxIndex) return newArr.push(item) }) return newArr }
let sortArray = [], newArr = [] let main = function main(arr) { if(arr.length === 0 ) return if(arr.length === 1) { let onlyValue = arr[0] const insertIndex = sortArray.length / 2 if(onlyValue > sortArray[insertIndex]) { sortArray.splice(insertIndex + 1, 0, onlyValue) } else { sortArray.splice(insertIndex, 0, onlyValue) }
console.log('res', sortArray) return }
if(arr.length > 1) { let { minValue, minIndex } = getMin(arr) let { maxValue, maxIndex } = getMax(arr) console.log( minValue, maxValue) if(sortArray.length % 2 === 0){ const insertIndex = sortArray.length / 2 sortArray.splice(insertIndex, 0, minValue, maxValue) console.log('sortArray', sortArray) } newArr = filterMinAndMax(minIndex, maxIndex, arr) console.log('newArr', newArr) }
main(newArr) }
main(arr)
|