Home Web Front-end JS Tutorial Detailed explanation of JavaScript queue principles and usage examples

Detailed explanation of JavaScript queue principles and usage examples

Dec 18, 2017 pm 01:31 PM
javascript js Example

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'];
Copy after login

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 = [];
}
Copy after login

As above:

this.dataStore = []; An empty array stores all elements in the queue.

2. The method of adding an element to the tail of the queue is as follows:


function enqueue(element) {
   this.dataStore.push(element);
}
Copy after login

3. The method of deleting the element of the head of the queue is as follows:


function dequeue() {
  return this.dataStore.shift()
}
Copy after login

4. Read the elements at the head of the queue as follows:


function front() {
  return this.dataStore[0];
}
Copy after login

5. Read the elements at the tail of the queue as follows:


function back() {
  return this.dataStore[this.dataStore.length - 1];
}
Copy after login

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;
}
Copy after login

7. Determine whether the queue is empty as follows:


function empty(){
  if(this.dataStore.length == 0) {
    return true;
  }else {
    return false;
  }
}
Copy after login

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;
    }
  }
};
Copy after login

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
Copy after login

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"];
Copy after login

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]
Copy after login

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]
Copy after login

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] = 7
Copy after login

Finally, 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];
Copy after login

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]);
     }
   }
}
Copy after login

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();
    }
  }
}
Copy after login

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;

Finally, all the JS codes are 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;
    }
  },
  /*
   * 根据个位或十位上的数值,将数字分配到相应队列的函数
   * @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]);
    }
  }
};
Copy after login

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);
Copy after login

相关推荐:

php中队列原理以及写文件的图文代码详解

详解JavaScript队列函数和异步执行

JavaScript队列函数和异步执行详解

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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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 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.

Learn best practice examples of pointer conversion in Golang Learn best practice examples of pointer conversion in Golang Feb 24, 2024 pm 03:51 PM

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.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

See all articles