


Detailed explanation of JavaScript queue principles and usage examples
A queue is a kind of list. The difference is that a queue can only insert elements at the end of the queue and delete elements at the beginning of the queue. Queues are used to store data arranged in order, first in, first out, which is different from stacks (last in, first out). In the stack, the last element pushed onto the stack is processed first. We can now imagine the queue as when we go to a restaurant to eat. Many people line up to eat, and the person at the front gets their meal first. Newcomers can only queue at the back. until it's their turn. This article mainly introduces the principles and usage of queues in JavaScript data structures and algorithms, explains the concepts and principles of queues in more detail, and analyzes the related operating techniques and precautions for implementing and using queues in JavaScript in the form of examples. Friends in need can refer to Next, I hope it can help everyone.
1: Operations on the queue
The queue has two main operations, inserting new elements into the tail of the queueenqueue( ) method and the dequeue() method that deletes the element at the head of the queue. In addition, we also have a method that reads the element at the head of the queue. This method we can call front()method. This method returns the head element and other methods.
After seeing the above description, many of us may think of arrays. There are also two methods in the array that have similar functions to the above methods. The push()
method in the array also adds new data to the back of the array. element, the shift()
method in the array can delete the first element in the array. The following code:
var arrs = []; arrs.push("a"); arrs.push("b"); console.log(arrs); // ["a","b"]; arrs.shift(); console.log(arrs); // ['b'];
Below we can use 2 of push()
and shift()
in the above array Method to encapsulate our queue Queue class;
1. We can first define a constructor Queue class, as follows:
##
function Queue() { this.dataStore = []; }
this.dataStore = []; An empty array stores all elements in the queue.
function enqueue(element) { this.dataStore.push(element); }
function dequeue() { return this.dataStore.shift() }
function front() { return this.dataStore[0]; }
function back() { return this.dataStore[this.dataStore.length - 1]; }
function toString() { var retStr = ""; for(var i = 0; i < this.dataStore.length; ++i) { retStr += this.dataStore[i] + "\n"; } return retStr; }
function empty(){ if(this.dataStore.length == 0) { return true; }else { return false; } }
function Queue() { this.dataStore = []; } Queue.prototype = { // 向队尾添加一个元素 enqueue: function(element) { this.dataStore.push(element); }, // 删除队首的元素 dequeue: function(){ return this.dataStore.shift(); }, // 读取队首的元素 front: function(){ return this.dataStore[0]; }, // 读取队尾的元素 back: function(){ return this.dataStore[this.dataStore.length - 1]; }, // 显示队列内的所有元素 toString: function(){ var retStr = ""; for(var i = 0; i < this.dataStore.length; ++i) { retStr += this.dataStore[i] + "\n"; } return retStr; }, // 判断队列是否为空 empty: function(){ if(this.dataStore.length == 0) { return true; }else { return false; } } };
var q = new Queue(); q.enqueue("a"); q.enqueue("b"); q.enqueue("c"); console.log(q.toString()); // a b c q.dequeue(); console.log(q.toString()); // b c console.log("Front of queue:" +q.front()); // b console.log("Back of queue:" +q.back()); // c
Two: Use queues to sort data
For example, for sorting numbers from 0 to 99, the principle is: Sort the numbers in the ones place first, and then sort the numbers in the tens place. Each number is divided into different boxes according to the value of the corresponding digit, and then the remainder method is used for the numbers in the ones place, and the division method is used for the numbers in the 10th digit. Then this sorting is called "radix sorting" . It's not the fastest sorting method, but it describes some interesting ways to use queues. For example, the following array:var nums = ["50","12","95","7","90","3","74","81","91","72"];
queues[0] = 50 或者 90 queues[1] = 81 或者 91 queues[2] = 12 或者 72 queues[3] = 3 queues[4] = 74 queues[5] = 95 queues[6] queues[7] = 7 queues[8] queues[9]
nums = [50,90,81,91,12,72,3,74,95,7]
queues[5] = 50 queues[9] = 90 queues[8] = 81 queues[9] = 91 queues[1] = 12 queues[7] = 72 queues[0] = 3 queues[7] = 74 queues[9] = 95 queues[0] = 7
nums = [3,7,12,50,72,74,81,90,91,95];
/* * 根据个位或十位上的数值,将数字分配到相应队列的函数 * @param digit * digit=1 表示先按个位来分配 * digit = 10 表示是按十位来分配的 * @param n 表示循环比较多少次 一般数组几个数字就比较多少次 */ distribute: function(nums,queues,n,digit){ for(var i = 0; i < n; ++i) { if(digit == 1) { queues[nums[i] % 10].enqueue(nums[i]); }else { queues[Math.floor(nums[i] / 10)].enqueue(nums[i]); } } }
// 收集数字的函数 collect: function(queues,nums,n) { var i = 0; for(var digit = 0; digit < n; ++digit) { while(!queues[digit].empty()) { nums[i++] = queues[digit].dequeue(); } } }
function Queue() { this.dataStore = []; } Queue.prototype = { // 向队尾添加一个元素 enqueue: function(element) { this.dataStore.push(element); }, // 删除队首的元素 dequeue: function(){ return this.dataStore.shift(); }, // 读取队首的元素 front: function(){ return this.dataStore[0]; }, // 读取队尾的元素 back: function(){ return this.dataStore[this.dataStore.length - 1]; }, // 显示队列内的所有元素 toString: function(){ var retStr = ""; for(var i = 0; i < this.dataStore.length; ++i) { retStr += this.dataStore[i] + "\n"; } return retStr; }, // 判断队列是否为空 empty: function(){ if(this.dataStore.length == 0) { return true; }else { return false; } }, /* * 根据个位或十位上的数值,将数字分配到相应队列的函数 * @param digit * digit=1 表示先按个位来分配 * digit = 10 表示是按十位来分配的 * @param n 表示循环比较多少次 一般数组几个数字就比较多少次 */ distribute: function(nums,queues,n,digit){ for(var i = 0; i < n; ++i) { if(digit == 1) { queues[nums[i] % 10].enqueue(nums[i]); }else { queues[Math.floor(nums[i] / 10)].enqueue(nums[i]); } } }, // 收集数字的函数 collect: function(queues,nums,n) { var i = 0; for(var digit = 0; digit < n; ++digit) { while(!queues[digit].empty()) { nums[i++] = queues[digit].dequeue(); } } }, dispArray: function(arr) { for(var i = 0; i < arr.length; ++i) { console.log(arr[i]); } } };
var q = new Queue(); q.enqueue("a"); q.enqueue("b"); q.enqueue("c"); console.log(q.toString()); q.dequeue(); console.log(q.toString()); console.log("Front of queue:" +q.front()); console.log("Back of queue:" +q.back()); var queues = []; for(var i = 0; i < 10; ++i) { queues[i] = new Queue(); } var nums = ["50","12","95","7","90","3","74","81","91","72"]; console.log("before radix sort: "); console.log(nums); q.distribute(nums,queues,10,1); q.collect(queues,nums,10); q.dispArray(nums); console.log("分割线"); q.distribute(nums,queues,10,10); q.collect(queues,nums,10); q.dispArray(nums);
相关推荐:
The above is the detailed content of Detailed explanation of JavaScript queue principles and usage 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

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



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

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

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

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.

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

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
