快速排序
function fast (arr) {
if (arr.length <= 1) {
return arr
}
let left = []
let right = []
let p = arr.splice(0, 1)[0]
for (let i = 0, l = arr.length; i < l; i++) {
if (p > arr[i]) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
return [].concat(fast(left), [p], fast(right))
}
冒泡排序
function pubble (arr) {
if (arr.length <= 1) {
return arr
}
for (let i = 0, l = arr.length; i < l - 1; i++) {
for (let j = i; j < l; j++) {
if (arr[i] > arr[j]) {
let temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return arr
}
插入排序
function insert (arr) {
for (let i = 1, l = arr.length; i < l; i++) {
let temp = arr[i]
let j = i - 1
while (j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j]
j--
}
arr[j + 1] = temp
}
return arr
}
选择排序
function selection (arr) {
let l = arr.length
for (let i = 0; i < l - 1; i++) {
let minIndex = i
for (let j = i; j < l; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j
}
}
let temp = arr[i]
arr[i] = arr[minIndex]
arr[minIndex] = temp
}
return arr
}
经典阶乘函数
function factorial(num){
if(num<=1){
return 1;
}else{
return num*arguments.callee(num-1);
}
}
console.log(factorial(4));//24
函数节流
delayFunc(fn, interval) {
let _self = fn;
let timer;
let firstTime = true;
return function () {
let args = arguments;
let _me = this;
if (firstTime) {
_self.apply(_me, args);
firstTime = false;
return false;
}
if (timer) {
return false;
}
timer = setTimeout(function () {
clearTimeout(timer);
timer = null;
_self.apply(_me, args);
}, interval || 500);
};
},