Home Web Front-end JS Tutorial Priority queue and circular queue in JavaScript data structure

Priority queue and circular queue in JavaScript data structure

Oct 28, 2017 am 09:23 AM
javascript js data structure

The examples in this article describe the priority queue and loopqueue of the JavaScriptdata structure. Share it with everyone for your reference, the details are as follows:

Priority Queue

Implement a priority queue: Set priority and then add the element in the correct position.

What we implement here is a minimum priority queue. Elements with a small priority value (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(&#39;a&#39;,2);
pqueue.enqueue(&#39;b&#39;,1);
pqueue.enqueue(&#39;c&#39;,2);
pqueue.enqueue(&#39;d&#39;,2);
pqueue.enqueue(&#39;e&#39;,1);
pqueue.print();
//[ QueueEle { element: &#39;b&#39;, priority: 1 },
// QueueEle { element: &#39;e&#39;, priority: 1 },
// QueueEle { element: &#39;a&#39;, priority: 2 },
// QueueEle { element: &#39;c&#39;, priority: 2 },
// QueueEle { element: &#39;d&#39;, priority: 2 } ]
Copy after login

Running results:

Add elements at the correct position: If the queue is empty, you can directly enqueue the elements. Otherwise, you need to compare the priority of this element 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=&#39;&#39;;
  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=[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;];
var winner=hotPotato(namelist,7);
console.log(winner+"获胜");
//淘汰c
//淘汰b
//淘汰e
//淘汰d
//a获胜
Copy after login

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.

The above is the detailed content of Priority queue and circular queue in JavaScript data structure. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

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

Compare complex data structures using Java function comparison Compare complex data structures using Java function comparison Apr 19, 2024 pm 10:24 PM

When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

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.

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

In-depth understanding of reference types in Go language In-depth understanding of reference types in Go language Feb 21, 2024 pm 11:36 PM

Reference types are a special data type in the Go language. Their values ​​do not directly store the data itself, but the address of the stored data. In the Go language, reference types include slices, maps, channels, and pointers. A deep understanding of reference types is crucial to understanding the memory management and data transfer methods of the Go language. This article will combine specific code examples to introduce the characteristics and usage of reference types in Go language. 1. Slices Slices are one of the most commonly used reference types in the Go language.

PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure Jun 03, 2024 am 09:58 AM

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Feb 23, 2024 am 10:49 AM

Overview of Java Collection Framework The Java collection framework is an important part of the Java programming language. It provides a series of container class libraries that can store and manage data. These container class libraries have different data structures to meet the data storage and processing needs in different scenarios. The advantage of the collection framework is that it provides a unified interface, allowing developers to operate different container class libraries in the same way, thereby reducing the difficulty of development. Data structures of the Java collection framework The Java collection framework contains a variety of data structures, each of which has its own unique characteristics and applicable scenarios. The following are several common Java collection framework data structures: 1. List: List is an ordered collection that allows elements to be repeated. Li

Hash table-based data structure optimizes PHP array intersection and union calculations Hash table-based data structure optimizes PHP array intersection and union calculations May 02, 2024 pm 12:06 PM

The hash table can be used to optimize PHP array intersection and union calculations, reducing the time complexity from O(n*m) to O(n+m). The specific steps are as follows: Use a hash table to map the elements of the first array to a Boolean value to quickly find whether the element in the second array exists and improve the efficiency of intersection calculation. Use a hash table to mark the elements of the first array as existing, and then add the elements of the second array one by one, ignoring existing elements to improve the efficiency of union calculations.

See all articles