排序算法
const arr = [9, 8, 4, 2, 5, 7, 10, 1, 0, 88];
const sort = (arr, desc) => {
const _arr = [];
for (let temp of arr) {
if (_arr.length === 0) {
_arr.push(temp);
} else {
if (temp <= _arr[0]) {
_arr.unshift(temp);
} else if (temp >= _arr[_arr.length - 1]) {
_arr.push(temp);
} else {
for (let j in _arr) {
if (temp > _arr[j] && temp < _arr[Number(j) + 1]) {
_arr.splice(Number(j) + 1, 0, temp);
break;
}
}
}
}
}
return desc ? _arr.reverse() : _arr;
};
console.time("sort");
const asc = sort(JSON.parse(JSON.stringify(arr)));
console.log(asc);
console.timeEnd("sort");
console.time("sortDesc");
const desc = sort(JSON.parse(JSON.stringify(arr)), true);
console.log(desc);
console.timeEnd("sortDesc");
document.getElementById("origin-div").innerHTML =
"原始:" + JSON.stringify(arr);
document.getElementById("asc-div").innerHTML = "升序:" + JSON.stringify(asc);
document.getElementById("desc-div").innerHTML = "降序:" + JSON.stringify(desc);