冒泡排序:
Array.prototype.bubbleSort = function () {
for (let i = 0; i < this.length - 1; i += 1) {
for (let j = 0; j < this.length - 1 - i; j += 1) {
if (this[j] > this[j + 1]) {
const temp = this[j]
this[j] = this[j + 1]
this[j + 1] = temp
}
}
}
}
const arr = [5, 1, 6, 3]
arr.bubbleSort()
console.log(arr)
快速排序
Array.prototype.fastSort = function () {
const sort = (arr) => {
if (arr.length < 2) {
return arr
}
let left = []
let right = []
let mid = arr[0]
for (let i = 1; i < arr.length; i++) {
if (arr[i] > mid) {
right.push(arr[i])
} else {
left.push(arr[i])
}
}
return [...sort(left), mid, ...sort(right)]
}
let newArr = sort(this)
for (let i = 0; i < this.length; i++) {
this[i] = newArr[i]
}
}
let arr = [4, 1, 2, 6, 8, 7, 3, 10, 9]
arr.fastSort()
console.log(arr)
选择排序
Array.prototype.selectSort = function () {
for (let i = 0; i < this.length - 1; i++) {
let indexMin = i;
for (let j = i; j < this.length; j++) {
if (this[j] < this[indexMin]) {
indexMin = j
}
}
if (indexMin !== i) {
let temp = this[i]
this[i] = this[indexMin]
this[indexMin] = temp
}
}
}
const arr = [5, 1, 6, 3]
arr.selectSort()
console.log(arr)
插入排序
Array.prototype.insertSort=function(){
for(let i=0;i<this.length;i++){
let temp=this[i]
let j=i
while(j>0){
if(this[j-1]>temp){
this[j]=this[j-1]
}
else{
break;
}
j--
}
this[j]=temp
}
}
const arr = [5, 1, 6, 3]
arr.insertSort()
console.log(arr)
图的深度优先遍历
const visited = new Set()
const dfs = (n) => {
console.log(n)
visited.add(n)
graph[n].forEach(c => {
if (!visited.has(c)) {
dfs(c)
}
})
}
dfs(2)