Detailed explanation of the JavaScript implementation method of heap
Definition of heap
A maximum (minimum) heap is a tree in which the key value of each node is not less than (greater than) the key value of its child (if it exists). The big heap is a complete binary tree and is also a maximum tree. The mini-heap is a completely binary tree and also a minimal tree.
In addition, remembering these two concepts is very important for writing code:
1. The relationship between parent nodes and child nodes: see the definition
2. Complete binary tree: refer to [2]
Basic operations
1. Build (build heap)
2. Insert
3. Delete (delete: the smallest or largest one)
Code implementation
First of all, there are two very important things before writing code Points:
1. An array can be used as the storage structure of the heap, which is very simple and easy to operate; 2. In addition, because the array is used as the storage structure, the relationship between parent and child nodes can be determined based on the index. Found each other easily.
For JavaScript, starting with 0 as the array index, the relationship is as follows:
nLeftIndex = 2 * (nFatherIndex+1) - 1; nRightIndex = 2* (nFatherIndex+1);
2. The concept of a complete binary tree can be referred to [2]. The leaf nodes are required to be filled from left to right before the next layer can be filled. This ensures that there is no need to modify the array Make large movements as a whole. This is also a shortcoming of random storage structures (arrays): after deleting an element, it is more time-consuming to move the entire element forward. This feature also causes the heap to add the last leaf node to the root node when deleting elements. Code implementation:
/****************************************************** * file : 堆 * author : "page" * time : "2016/11/02" *******************************************************/ function Heap() { this.data = []; } Heap.prototype.print = function () { console.log("Heap: " + this.data); } Heap.prototype.build = function(data){ // 初始化 this.data = []; if (!data instanceof Array) return false; // 入堆 for (var i = 0; i < data.length; ++i) { this.insert(data[i]); } return true; } Heap.prototype.insert = function( nValue ){ if (!this.data instanceof Array) { this.data = []; } this.data.push(nValue); // 更新新节点 var nIndex = this.data.length-1; var nFatherIndex = Math.floor((nIndex-1)/2); while (nFatherIndex > 0){ if (this.data[nIndex] < this.data[nFatherIndex]) { var temp = this.data[nIndex]; this.data[nIndex] = this.data[nFatherIndex]; this.data[nFatherIndex] = temp; } nIndex = nFatherIndex; nFatherIndex = Math.floor((nIndex-1)/2); } } Heap.prototype.delete = function( ){ if (!this.data instanceof Array) { return null; } var nIndex = 0; var nValue = this.data[nIndex]; var nMaxIndex = this.data.length-1; // 更新新节点 var nLeaf = this.data.pop(); this.data[nIndex] = nLeaf; while (nIndex < nMaxIndex ){ var nLeftIndex = 2 * (nIndex+1) - 1; var nRightIndex = 2 * (nIndex+1); // 找最小的一个子节点(nLeftIndex < nRightIndex) var nSelectIndex = nLeftIndex; if (nRightIndex < nMaxIndex) { nSelectIndex = (this.data[nLeftIndex] > this.data[nRightIndex]) ? nRightIndex : nLeftIndex; } if (nSelectIndex < nMaxIndex && this.data[nIndex] > this.data[nSelectIndex] ){ var temp = this.data[nIndex]; this.data[nIndex] = this.data[nSelectIndex]; this.data[nSelectIndex] = temp; } nIndex = nSelectIndex; } return nValue; } // test var heap = new Heap(); heap.build([1, 3, 5, 11, 4, 6, 7, 12, 15, 10, 9, 8]); heap.print(); // insert heap.insert(2); heap.print(); // delete heap.delete(); heap.print();
Some summary about JavaScript
Here are the oriented An implementation method of objects, it doesn’t feel too elegant. I don’t know if there is a better way of expressing and writing; I learned several uses of arrays: the push and pop operations are so easy to use;
The method of judging arrays was also temporarily searched from the Internet (instanceof). I was not very impressed. If I don’t use it, I will probably forget it next time.
[3]>Data Structure: Heap
Summary
JavaScript’s array implements push and pop operations. Many other languages also provide similar data structures and operations (such as C++’s Vector), and also support random operations. So, I began to think that if the concept of automatic sorting is simply added to these structures, then a heap can be easily solved. Later, when I saw the make_heap of C++ STL, I realized that I knew too little, but I was glad that my way of thinking was right. of. I didn’t check JavaScript, I think it exists or it is easy to implement;
After I implemented it myself, I found that this structure is also very simple, as long as you are willing to get in close contact with it once; The details of JavaScript are still not there I know too much about it. For example, you need to read more information about the application of arrays before you can use it; I still haven’t come into contact with the soul of JavaScript, and the essence requires continuous learning and practice;These codes, as long as you understand the concepts and programming The basics can be written out. However, the code can be written more concisely. For example, when the delete function finds the smallest child node, the indexes of the left and right nodes do not need to be compared. The one on the left must be smaller. It feels like the code part can still be optimized and streamlined.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
