javascript中排序算法大全
互联网 2021/4/8 12:38:22 次
javascript当中存在两个API:sort和indexOf来实现排序和搜索,但知其然还要知其所以然,下面来看下javascript如何实现排序和搜索算法。
排序算法
1.冒泡排序
时间复杂度:O(n^2).
Array.prototype.bubbleSort = function () { for (let i = 0; i < this.length - 1; i++) { for (let j = 0; j < this.length - 1 - i; j++) { if (this[j] > this[j + 1]) { const temp = this[j]; this[j] = this[j + 1]; this[j + 1] = temp; } } } }; var arr = [3, 2, 4, 9, 1]; arr.bubbleSort(); console.log(arr);
2.选择排序
时间复杂度:O(n^2).
Array.prototype.selectionSort = function () { for (let i = 0; i < this.length - 1; i++) { let indexMin = i; for (let j = i; j < this.length - 1; j++) { if (this[j] < this[indexMin]) { indexMin = j; } } const temp = this[i]; this[i] = this[indexMin]; this[indexMin] = temp; } }; const arr = [3, 4, 1, 2, 5]; arr.selectionSort(); console.log(arr);
3.插入排序
时间复杂度:O(n^2).
Array.prototype.insertionSort = function () { for (let i = 1; 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 = [3, 4, 1, 2, 5]; arr.insertionSort(); console.log(arr);
4.归并排序
分的时间复杂度是O(logN)
合的时间复杂度是O(n)
时间复杂度:O(n*logN)
Array.prototype.mergeSort = function () { const rec = (arr) => { //递归判断条件 if (arr.length === 1) { return arr; } //先分数组 const mid = Math.floor(arr.length / 2); const left = arr.slice(0, mid); const right = arr.slice(mid, arr.length); const orderLeft = rec(left); const orderRight = rec(right); const res = []; //再治数组 while (orderLeft.length || orderRight.length) { if (orderLeft.length && orderRight.length) { res.push( orderLeft[0] < orderRight[0] ? orderLeft.shift() : orderRight.shift(), ); } else if (orderLeft.length) { res.push(orderLeft.shift()); } else if (orderRight.length) { res.push(orderRight.shift()); } } //数组合并 return res; }; const res = rec(this); res.forEach((n, i) => { this[i] = n; }); }; var arr = [3, 2, 4, 9, 1]; arr.mergeSort(); console.log(arr);

关于找一找教程网
本站文章仅代表作者观点,不代表本站立场,所有文章非营利性免费分享。
本站提供了软件编程、网站开发技术、服务器运维、人工智能等等IT技术文章,希望广大程序员努力学习,让我们用科技改变世界。
[javascript中排序算法大全]http://www.zyiz.net/tech/detail-153795.html
您可能感兴趣的文章:
- 2019-07-07Java编写中容易搞错的一些东西
- 2021-04-12Java中数组是什么?数组的定义方式有哪些?如何使用?数组元素的默认值分别是什么?数组的特点、 数组中常见的异常、数组的内存分析、数组中常见操作
- 2021-04-12shell常用命令
- 2021-04-12一些关于内存泄露、栈溢出和野指针的内容(头秃
- 2021-04-1214 | 进程数据结构(下):项目多了就需要项目管理系统
- 2021-04-12node升级--windows
- 2021-04-12安卓内存监控apk,你的技术真的到天花板了吗?深度好文
- 2021-04-12我的shell脚本实战-编写一个系统发布脚本
- 2021-04-12windows下protobuf踩坑
- 2021-04-12Windows上两个host文件的位置

扫描二维码或查找【程序员编程王】
可以随时随地学编程啦!
共有 条评论 网友评论