共计 1468 个字符,预计需要花费 4 分钟才能阅读完成。
比拟罕用且比拟实用的算法,面试、工作中很多时候都能用到。当然还有一些其余算法就不一一列举了,四个字:多多实际
随机数组洗牌
function foo(arr){var newarr = arr.slice();
for(let i=0,len = arr.length;i<len;i++){let index = Math.floor(Math.random() * len);
[newarr[i], newarr[index]] = [newarr[index], newarr[i]];
}
return newarr;
}
console.log(foo([1, 2, 3, 4, 5, 6, 7]));
简略的日期字符串排序
var date = ['2010-03-19', '2020-04-01', '2015-09-07', '2015-09-08'];
var aa =date.sort((a,b)=> Date.parse(b) - Date.parse(a) );
console.log(aa);
递归实现数组扁平化
function flatArr(arr){let tempArr=[];
arr.forEach(item => {if (Array.isArray(item)){tempArr= tempArr.concat(flatArr(item));
}else{tempArr.push(item);
}
});
return tempArr;
}
console.log(flatArr([1,2,[3,4,[5,[[6]]]]]));
极简版数组扁平化
[1,2,3,[4,5,[6,[[7]]]]].flat(Infinity);
记录数组项反复次数
var arr = ['张三', '张三', 'zzz', '历史', 'zzz', 'zzz'];
function getRepeatTimes() {var Obj = {};
arr.forEach(item => {Obj[item] = (Obj[item] + 1) || 1; //Obj[item] 如不存在,+ 1 为 NaN
})
return Obj;
}
console.log(getRepeatTimes(arr))
冒泡排序
function arrSort(arr = []) {
let len = arr.length;
for (let i = 0; i < len; i++) {for (let k = 0; k < len - 1 - i; k++) {if (arr[k] > arr[k + 1]) {[arr[k], arr[k + 1]] = [arr[k + 1], arr[k]];
}
}
}
return arr;
}
console.log(arrSort([5, 3, 6, 1, 9, 4, 9, 4, 8, 7, 8, 6, 2]));
疾速排序 (适宜数据量大的排序)
function quickSort(arr) {if (arr.length <= 1) {return arr;}
var midIndex = Math.floor(arr.length / 2);
var mid = arr.splice(midIndex, 1)[0]; // 获得两头基准并删除掉
var left = [],right = [];
for (var i = 0; i < arr.length; i++) {if (arr[i] <= mid) { // 把基准两边的数据别离寄存到不同分区
left.push(arr[i]);
} else {right.push(arr[i]);
}
}
return quickSort(left).concat([mid], quickSort(right));
}
console.log(quickSort([4, 8, 7, 3, 5, 1, 2, 9, 0, 7, 5]))
正文完
发表至: javascript
2020-11-29