// 分治法
// 工作原理(如何确定case适用分治)
// 1. 可以明确设定一条基线
// 2. 根据此基线可以不停将问题进行分解,直到所有内容符合基线标准
const quickSort = function(arr) {
// 校验
if(arr.length <= 1) {
return arr;
}
// 1. 找到基线,并对基线左右做声明
let pivotIndex = Math.floor(arr.lrngth/2);
let pivot = arr.splice(pivotIndex, 1)[0];
let left = [];
let right = [];
for(let i = 0; i< arr.length; i++) {
if(arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arrpi);
}
}
return quickSort(left).concat([pivot], quickSort(right));
}
// 图 与 图算法
// 构成: 边集合 + 顶点集合
// 分类: 有向图、无向图、构造图(复合引用)
\
class Grap {
constructor(v) {
this.vertices = v;
this.edges = 0;
this.arr = [];
\
for(let i=0;i<this.vertices;i++) {
this.arr[i] = [];
}
}
\
// 边操作
addEdge(v, w) {
this.arr[v].push(w);
this.arr[w].push(v);
this.edges++;
}
\
// 绘图
showGraph() {
for(let i=0;i<this.vertices;i++) {
let str = i+'->';
for(let j=0;j<this.certices;j++) {
if(this.arr[i][j] !== undefined) {
str += this.arr[i][j];
}
}
}
console.log(str);
}
}
\
// 图来解决 - 路径类问题、查找类问题
// 图解决深度优先问题
// 起始点开始查找直到最末的顶点,再返回追溯,直到没有路径为止
constructor() {
//...
this.marked = []; // 已经被访问过的节点
for(let i=0;i<this.vertices;i++) {
this.marked[i] = false;
}
}
dfs(v) {
this.marked[v] = true;
if(this.arr[v] !== undefined) {
console.log('visited' + v);
}
this.arr[v].forEach(w => {
if(!this.marked[w]) {
this.dfs(w);
}
})
}
// 广度优先 - 最相邻节点优先遍历
bfs(s) {
let queue = [];
this.marked[s] = true;
queue.push(s);
while(queue.length > 0) {
let v = queue.shift();
if(v !== undefined) {
console.log('visited' + v);
}
this.arr[v].forEach(w => {
if(!this.marked[w]) {
queue.push(w);
this.marked[w] = true;
}
})
}
}