


Detailed explanation of JavaScript priority queue and circular queue examples
This article mainly introduces the priority queue and circular queue of the JavaScript data structure. It analyzes the principles, definitions and usage of the priority queue and circular queue in the javascript data structure in detail in the form of examples. Friends in need can refer to it. I hope Can help everyone.
Priority Queue
Implement a priority queue: set the priority, then add elements at the correct position.
What we implement here is a minimum priority queue, and elements with small priority values (high priority) are placed in front of the queue.
//创建一个类来表示优先队列 function Priorityqueue(){ var items=[];//保存队列里的元素 function QueueEle(e,p){//元素节点,有两个属性 this.element=e;//值 this.priority=p;//优先级 } this.enqueue=function(e,p){//添加一个元素到队列尾部 var queueEle=new QueueEle(e,p); var added=false; //priority小的优先级高,优先级高的在队头 if(this.isEmpty()){ items.push(queueEle); }else{ for(var i=0;i<items.length;i++){ if(items[i].priority>queueEle.priority){ items.splice(i,0,queueEle); added=true; break; } } if(!added){ items.push(queueEle); } } } this.isEmpty=function(){ return items.length==0; } this.dequeue=function(){ return items.shift(); } this.clear=function(){ items=[]; } this.print=function(){ console.log(items); } this.mylength=function(){ return items.length; } } var pqueue=new Priorityqueue(); pqueue.enqueue('a',2); pqueue.enqueue('b',1); pqueue.enqueue('c',2); pqueue.enqueue('d',2); pqueue.enqueue('e',1); pqueue.print(); //[ QueueEle { element: 'b', priority: 1 }, // QueueEle { element: 'e', priority: 1 }, // QueueEle { element: 'a', priority: 2 }, // QueueEle { element: 'c', priority: 2 }, // QueueEle { element: 'd', priority: 2 } ]
Running results:
Add elements at the correct position: If the queue is empty, you can directly enqueue the elements. Otherwise, the priority of this element needs to be compared with other elements. When an item with a lower priority than the element to be added is found, the new element is inserted before it. In this way, for other elements with the same priority but added to the queue first, we also follow the first-in-first-out principle.
Maximum priority queue: Elements with larger priority values are placed at the front of the queue.
Circular Queue
Implement the drumming and flower passing game.
//创建一个类来表示队列 function Queue(){ var items=[];//保存队列里的元素 this.enqueue=function(e){//添加一个元素到队列尾部 items.push(e); } this.dequeue=function(){//移除队列的第一项,并返回 return items.shift(); } this.front=function(){//返回队列的第一项 return items[0]; } this.isEmpty=function(){//如果队列中部包含任何元素,返回true,否则返回false return items.length==0; } this.mylength=function(){//返回队列包含的元素个数 return items.length; } this.clear=function(){//清除队列中的元素 items=[]; } this.print=function(){//打印队列中的元素 console.log(items); } } //击鼓传花 function hotPotato(namelist,num){ var queue=new Queue(); for(var i=0;i<namelist.length;i++){ queue.enqueue(namelist[i]); } var eliminated=''; while(queue.mylength()>1){ for(i=0;i<num;i++){ queue.enqueue(queue.dequeue()); } eliminated=queue.dequeue(); console.log("淘汰"+eliminated); } return queue.dequeue(); } var namelist=['a','b','c','d','e']; var winner=hotPotato(namelist,7); console.log(winner+"获胜"); //淘汰c //淘汰b //淘汰e //淘汰d //a获胜
Run result:
Get a list and add all the names in it to the queue. Given a number, the queue is iterated over. Remove an item from the head of the queue and add it to the tail of the queue to simulate a circular queue. Once the number of passes reaches a given number, the person who got the flower is eliminated. When there is only one person left in the end, he is the winner.
Related recommendations:
Detailed explanation of how priority queue is implemented in JDK
Circular queue code implemented using arrays in javascript_javascript skills
The above is the detailed content of Detailed explanation of JavaScript priority queue and circular queue examples. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

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

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Lambda expression breaks out of the loop, specific code examples are needed. In programming, the loop structure is an important syntax that is often used. However, in certain circumstances, we may want to break out of the entire loop when a certain condition is met within the loop body, rather than just terminating the current loop iteration. At this time, the characteristics of lambda expressions can help us achieve the goal of jumping out of the loop. Lambda expression is a way to declare an anonymous function, which can define simple function logic internally. It is different from an ordinary function declaration,

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

This article will explain in detail how PHP returns all the values of an array to form an array. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Using the array_values() function The array_values() function returns an array of all the values in an array. It does not preserve the keys of the original array. $array=["foo"=>"bar","baz"=>"qux"];$values=array_values($array);//$values will be ["bar","qux"]Using a loop can Use a loop to manually get all the values of the array and add them to a new

Iterator interface The Iterator interface is an interface used to traverse collections. It provides several methods, including hasNext(), next() and remove(). The hasNext() method returns a Boolean value indicating whether there is a next element in the collection. The next() method returns the next element in the collection and removes it from the collection. The remove() method removes the current element from the collection. The following code example demonstrates how to use the Iterator interface to iterate over a collection: Listnames=Arrays.asList("John","Mary","Bob");Iterator
