参考文章:
Array.prototype.bubbleSort = function () {
for (let i = 0; i < this.length - 1; i++) {
let hasSwapped = false // 本轮是否有交换行为
for (let j = 0; j < this.length - 1 - i; j++) {
if (this[j] > this[j + 1]) {
hasSwapped = true
const temp = this[j]
this[j] = this[j + 1]
this[j + 1] = temp
}
}
// 若本轮没有交换行为,则无需再进行下一轮遍历
if (!hasSwapped) {
break;
}
}
}
const arr = [5, 4, 3, 2, 1]
arr.bubbleSort()
console.log(‘arr‘, arr)
Array.prototype.selectionSort = 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) {
const temp = this[i]
this[i] = this[indexMin]
this[indexMin] = temp
}
}
}
const arr = [5, 4, 3, 2, 1]
arr.selectionSort()
console.log(‘arr‘, arr)
Array.prototype.insertionSort = function () {
for (let i = 1; i < this.length; i++) {
const num = this[i];
for (let j = i - 1; j >= 0; j--) {
if (num < this[j]) {
this[j + 1] = this[j]
}
else {
break
}
}
this[j + 1] = num
}
}
const arr = [5, 4, 3, 2, 1]
arr.insertionSort()
console.log(‘arr‘, arr)
Array.prototype.mergeSort = function () {
// 终点
if (this.length === 1) {
return this
}
// 分
const mid = Math.floor(this.length / 2)
const left = this.slice(0, mid)
const right = this.slice(mid)
left.mergeSort()
right.mergeSort()
// 合
let res = []
while (left.length > 0 || right.length > 0) {
if (left.length > 0 && right.length > 0) {
left[0] < right[0] ? res.push(left.shift()) : res.push(right.shift())
}
else if (left.length > 0) {
res.push(left.shift())
} else {
res.push(right.shift())
}
}
// res 拷贝到 this
res.forEach((item, i) => {
this[i] = item
})
}
const arr = [5, 4, 3, 2, 1]
arr.mergeSort()
console.log(‘arr‘, arr)
Array.prototype.quickSort = function () {
// end: 包括
const rec = (start, end) => {
if (end <= start) {
return
}
const pivot = this[start]
let i = start + 1
let j = end
while (i < j) {
while (this[i] <= pivot && i < j) {
i++
}
while (this[j] >= pivot && i < j) {
j--
}
// 若i<j,i和j交换
if (i < j) {
let temp = this[i]
this[i] = this[j]
this[j] = temp
}
}
// i == j 的情况
if (this[i] < pivot) {
// i和pivot交换
let temp = this[i]
this[i] = this[start]
this[start] = temp
rec(start, i - 1)
rec(i + 1, end)
} else {
// i-1和pivot交换
let temp = this[i - 1]
this[i - 1] = this[start]
this[start] = temp
rec(start, i - 2)
rec(i, end)
}
}
rec(0, this.length - 1)
}
const arr = [3, 1, 5, 4, 2]
arr.quickSort()
console.log(‘arr‘, arr)
JavaScript 实现排序算法(全网最易理解,前端面试必问,含动画)
原文:https://www.cnblogs.com/xuehaoyue/p/14344343.html