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 = []; }As above:
this.dataStore = []; An empty array stores all elements in the queue.
function enqueue(element) { this.dataStore.push(element); }3. The method of deleting the element of the head of the queue is as follows:
function dequeue() { return this.dataStore.shift() }4. Read the elements at the head of the queue as follows:
function front() { return this.dataStore[0]; }5. Read the elements at the tail of the queue as follows:
function back() { return this.dataStore[this.dataStore.length - 1]; }6. Display all elements in the queue
function toString() { var retStr = ""; for(var i = 0; i < this.dataStore.length; ++i) { retStr += this.dataStore[i] + "\n"; } return retStr; }7. Determine whether the queue is empty as follows:
function empty(){ if(this.dataStore.length == 0) { return true; }else { return false; } }The following is the complete JS code as follows:
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; } } };We can now test the above code: as follows:
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"];1. After radix sorting - units sorting, the numbers are distributed in different boxes. (In JS, we can assign it to different Queue instance classes). As follows
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]According to the order of the boxes, the results after sorting the first ones digit of the numbers are as follows:
nums = [50,90,81,91,12,72,3,74,95,7]2. Then distribute the results after the last sorting to different boxes according to the value in the tens digit. As follows:
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] = 7Finally, take out the numbers in the box and form a new list, which is the sorted number. As follows: can be generated as follows:
nums = [3,7,12,50,72,74,81,90,91,95];Using the queue list box as above, this algorithm can be implemented. We need 10 queues, each queue corresponds to A number, save all queues in an array, use remainder and division operations to determine the ones and tens digits. The remainder of the algorithm adds the numbers to the corresponding queue, reorders them based on the ones-digit value, then sorts them based on the tens-digit value, and adds the sorted numbers as a result. The following function allocates numbers to the corresponding queue according to the value in the ones or tens place.
/* * 根据个位或十位上的数值,将数字分配到相应队列的函数 * @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]); } } }The following is the function to collect numbers from the queue as follows:
// 收集数字的函数 collect: function(queues,nums,n) { var i = 0; for(var digit = 0; digit < n; ++digit) { while(!queues[digit].empty()) { nums[i++] = queues[digit].dequeue(); } } }Since many steps are omitted above, The description may not be very clear. Let's take a look at the flow chart first, combine it with the flow chart, and finally combine it with all the JS code to understand the basic principle of "radix sorting"; below we can look at the following flow chart;
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]); } } };The following is a test of the "radix sort" JS code ;The following code:
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!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

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

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