const _quickSort = array => {
// 边界情况:数组长度小于等于1
if(array.length <= 1) return array;
const midIndex = Math.floor(array.length / 2); //中间元素的下标
const midValue = array.splice(midIndex, 1)[0]; // splice返回删除元素组成的数组。
const left = [], right = []; //左右数组
for(let num of array) {
if(num > midValue) {
right.push(num);
} else {
left.push(num);
}
}
// 递归左右数组进行排序,并拼接返回
return [..._quickSort(left), midValue, ..._quickSort(right)];
}
2、冒泡排序
const bubbleSort = array => {
const len = array.length;
// 数组长度为n,只需要进行n-1次排序即可
for (let i = 0; i < len - 1; i++){
let flag = true; // 数组已经满足升序,flag便不会置为false,也就意味着直接跳出了外层循环排序的过程。
for(let j = 0; j < len - i; j++) {
if(array[j] > array[j+1]) {
[array[j], array[j+1]] = [array[j+1], array[j]];
flag = false;
}
}
// 无调整数组元素排序时,说明数组已经有序,直接终止循环即可。
if(flag) break;
}
return array;
}
FED19 发布订阅模式
请补全JavaScript代码,完成"EventEmitter"类实现发布订阅模式。
注意:
1. 同一名称事件可能有多个不同的执行函数
2. 通过"on"函数添加事件
3. 通过"emit"函数触发事件
// 定义发布订阅模式类
class EventEmitter {
constructor() {
this.events = {}; // 定义事件管理库
}
// 监听者:监听新增的事件名,以及对应的回调事件,并放到事件库中
on(name, callback) {
if(this.events[name]) {
this.events[name].push(callback);
} else {
this.events[name] = [callback];
}
}
// 发布者:让某一个名为name的事件行为执行,该事件名下可能有多个回调函数
emit(name) {
if(this.events[name]) {
this.events[name].forEach(callbackItem => callbackItem());
}
}
}



