<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function bubbleSort(arr) {
let len = arr.length;
for (var i = 0; i < len; i++) {
for (var j = 0; j < len - 1; j++) {
if (arr[j] > arr[j + 1]) { // 相邻元素两两对比
var temp = arr[j + 1]; // 元素交换
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
return arr
}
console.log(bubbleSort([1, 2, 3, 2, 4, 9, 5, 4, 7]));
let arr = '111'
console.log(arr.split(','));
console.log(Array.from(arr));
// JS经典算法:
// 1、字符串颠倒
str.split('').reverse().join('')
// 2、不借助中间量,颠倒a、b
a = [b, b = a][0]
// 3、快速获取数组的最大值、最小值
Array.prototype.max = function () {
return Math.max.apply(null, this)
}
Array.prototype.min = function () {
return Math.min.apply(null, this)
}
// 4、模拟数组的一些方法
// 4.0 先扩充类型的基本功能
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
}
return this;
}
// 4.1 pop()方法:删除数组最后一个元素,并返回该元素
Array.method('pop', function () {
return this.splice(this.length - 1, 1)[0]
})
// 4.2 push()方法:在数组末尾添加元素,并返回新数组的长度
// Array.method('mypush', function () {
// this.splice.apply(this, [this.length, 0]).
// concact(Array.prototype.slice(arguments))
// return this.length
// })
// 4.3 shift()方法:删除数组第一个元素,并返回该元素
Array.method('shift', function () {
return this.splice(0, 1)[0]
})
// 4.4 unshift()方法:在数组前面添加新元素,并返回该元素
Array.method('unshift', function () {
})
// 5、数组去重
// 5.1 利用对象判断去重
Array.prototype.fillRepeat = function () {
var result = []
var hash = {}
for (var i = 0; i < this.length; i++) {
if (hash[this[i]] === undefined) {
result.push(this[i])
}
hash[this[i]] = true
}
return result
}
// 5.2 利用数组下标去重
Array.prototype.fillRepeat = function () {
var result = []
for (var i = 0; i < this.length; i++) {
if (this.indexOf(this[i]) === i) {
result.push(this[i])
}
}
return result
}
// 5.3 先排序,后去重
Array.prototype.fillRepeat = function {
var result = []
this.sort()
for (var i = 0; i < this.length; i++) {
if (this[i] !== result[result.length - 1]) {
result.push(this[i])
}
}
return result
}
// 6、数组排序
// 6.1 快速排序
function quickSort(arr) {
if (arr.length <= 1) return arr
var lfArr = [], rtArr = [], q = arr[0]
for (var i = 1; i < arr.length; i++) {
if (arr[i] < q) {
lfArr.push(arr[i])
} else {
rtArr.push(arr[i])
}
}
return quickSort(lfArr).concact(q, quickSort(rtArr))
}
// 6.2 冒泡排序
Array.prototype.bubbleSort = function () {
var tem;
for (var i = 0; i < this.length - 1; i++) {
for (var j = 0; j < this.length - i - 1; j++) {
if (this[j] > this[j + 1]) {
tem = this[j];
this[j] = this[j + 1];
this[j + 1] = tem;
}
}
}
return this;
}
// 6.3 根据不同的类型进行排序
by = function (a, b) {
if (a === b) return 0
if (typeof a === typeof b) {
return a < b ? -1 : 1
}
return typeof a < typeof b ? -1 : 1
}
</script>
</body>
</html>
js常见的排序算法
最新推荐文章于 2024-07-15 18:41:44 发布