先定义一个函数用于产生随机数数组
const generateArr = (len, rdm, arr = []) => {
for (let i = 0; i < len; i++) {
arr.push(parseInt(Math.random() * rdm))
}
return arr
}
const arr = generateArr(6, 100)
console.log(arr) // [ 75, 11, 27, 69, 51, 22 ]
选择排序
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[i]) {
[arr[i], arr[j]] = [arr[j], arr[i]]
}
}
}
console.log(arr) // [ 11, 22, 27, 51, 69, 75 ]
冒泡排序
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
}
}
}
网友评论