下面提供两种数组排序方法
try {
/**
* 排序断言
*/
{
let arr = []
function arrData(num) {
for (let i = 0; i < num; i++) {
arr[i] = Math.floor(Math.random() * num + 1)
}
}
arrData(1000)
console.log(arr)
function jssort(myArr) {
let date1=new Date().getTime()
console.log(`${myArr.length}长度冒泡排序耗时`)
for (let i = 0; i < myArr.length - 1; i++) { //要循环多少次
for (let j = 0; j < myArr.length - 1; j++) { //要移动几次
if (myArr[j] > myArr[j + 1]) { [myArr[j], myArr[j + 1]] = [myArr[j + 1], myArr[j]] }
}
}
console.log(`${myArr.length}长度冒泡排序耗时${new Date().getTime()-date1}`)
return myArr;
}
console.log(jssort(arr))
function selectSort(myArr) {
let date1=new Date().getTime()
console.log(`${myArr.length}长度选择排序耗时`)
let minIndex, temp; var len = myArr.length;
for (let i = 0; i < myArr.length - 1; i++) {
minIndex = i;
for (let j = i + 1; j < myArr.length; j++) {
if (myArr[j] < myArr[minIndex]) { minIndex = j; }
} [myArr[i], myArr[minIndex]] = [myArr[minIndex], myArr[i]]
}
console.log(`${myArr.length}长度冒泡排序耗时${new Date().getTime()-date1}`)
return myArr;
}
console.log(selectSort(arr))
}
} catch (error) {
}
耗时对比测试