當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS数据结构与算法——插入排序
生活随笔
收集整理的這篇文章主要介紹了
JS数据结构与算法——插入排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、圖解排序過程
二、代碼實現
三、完整代碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><script>// 創建列表類function ArrayList() {// 屬性this.array = []// 方法// 將數據可以插入到數組中的方法ArrayList.prototype.insert = function (item) {this.array.push(item)}ArrayList.prototype.toString = function () {return this.array.join('-')}// 交換兩個位置的數據ArrayList.prototype.swap = function (m, n) {var temp = this.array[m]this.array[m] = this.array[n]this.array[n] = temp}// 實現排序算法// 冒泡排序ArrayList.prototype.bubbleSort = function () {// 1.獲取數組的長度var length = this.array.length// 2.反向循環,因此次數越來越少for (var j = length - 1; j >= 0; j--) {// 第一次進來: i = 0, 比較 0 和 1 位置的兩個數據,如果0位置大于 1位置的數據 交換兩個的位置// 最后一次進來:i = length - 2, 比較length - 2 和 length - 1 的兩個數據// 3.根據i的次數,比較到i的位置for (var i = 0; i < j; i++) {if (this.array[i] > this.array[i + 1]) {// 4.如果 i 位置比 i+1 位置的數據大,就交換位置// 前一個數字 > 后一個數字, 兩者交換位置this.swap(i, i + 1)}}}}// 選擇排序ArrayList.prototype.selectionSort = function () {// 1.獲取數組的長度let length = this.array.length// 2.外層循環:從0位置開始取數據for (let j = 0; j < length - 1; j++) {// 內層循環,從i+1位置開始,和后面的數據進行比較let min = j // 最小值的下標for (let i = min + 1; i < length; i++) {if (this.array[min] > this.array[i]) {// 如果當前下標保存的最小值 > 當前遍歷的項,// 說明當前遍歷項才是最小的值,那么保存當前遍歷項的下標min = i}}this.swap(min, j)}}// 插入排序ArrayList.prototype.insertionSort = function () {// 1.獲取數組的長度let length = this.array.length// 2.外層循環:從第1個位置開始獲取數據,向前面局部有序的部分進行插入for (let i = 1; i < length; i++) {// 3.內層循環:獲取i位置的數字,和前面的數字依次進行比較,let temp = this.array[i]let j = i// 只要temp前面的數字比temp大并且temp前面的數字的下標>0// (因為就j=0的話進入循環,j--后下標變成了-1,所以要滿足j>0才能進入循環),// 就把temp前面的數字往后移動1位while (this.array[j - 1] > temp && j > 0) {this.array[j] = this.array[j - 1] // 把大的數字往后挪j--}// 4.把比較的數據temp放到j位置this.array[j] = temp}}// 希爾排序// 快速排序}// 測試var list = new ArrayList()// 插入元素list.insert(66)list.insert(88)list.insert(12)list.insert(87)list.insert(100)list.insert(5)list.insert(566)list.insert(23)alert(list)// 驗證冒泡排序// list.bubbleSort()// list.selectionSort()list.insertionSort()alert(list) </script> </body> </html>總結
以上是生活随笔為你收集整理的JS数据结构与算法——插入排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Nodejs之http模块详解
- 下一篇: 二、uniapp项目(分段器的使用、sc