Queues & Priority Queues - Beau teaches JavaScript

**Creating and Working with Queues**

A queue is a fundamental data structure that follows the First-In-First-Out (FIFO) principle, where elements are added to the end of the queue and removed from the front. In this article, we will explore how to create and work with queues using JavaScript.

**Basic Queue Operations**

To create a basic queue, we can use an array to store the elements. We can add elements to the queue by using the `enqueue` function, which takes two arguments: the element to be added and its priority (if applicable). For example, if we want to enqueue an item with priority 5, we would pass in an array `[item, 5]`. The `enqueue` function returns the updated queue.

Once we have added elements to the queue, we can retrieve them using the `dequeue` function. This function removes and returns the element at the front of the queue. If we want to print all elements in the queue without removing them, we can use the `dq` function, which simply prints the elements at the beginning of the array.

For example, if we have a queue with `[a, b, c]`, calling `dequeue` would return `a`, and then calling `dq` again would print the remaining elements: `[b, c]`.

**Priority Queues**

A priority queue is similar to a basic queue but adds an additional layer of complexity through prioritization. When enqueueing an item into a priority queue, we also pass its priority as a second argument. This allows us to determine the order in which items are added to the queue.

For example, if we want to enqueue two items with different priorities, we would pass in arrays `[item1, priority1]` and `[item2, priority2]`. The item with the higher priority will be added to the front of the queue, while items with lower priorities will be added after them.

However, when printing elements from a priority queue, the order is determined by their priority. If two or more items have the same priority, they are printed in the order they were originally enqueued.

**Priority Queue Implementation**

To implement a priority queue in JavaScript, we can use an array to store the elements and their priorities. We can add elements to the queue using the `enqueue` function, which checks the priority of each element as it is added to determine its position in the queue.

Here's an example implementation:

```javascript

function pq(element) {

if (queue.length === 0 || element[1] > queue[0][1]) {

queue.push(element);

} else {

for (let i = 0; i < queue.length; i++) {

if (element[1] > queue[i][1]) {

break;

}

}

queue.splice(i, 0, element);

}

}

function dequeue() {

const removedElement = queue.shift();

return removedElement;

}

function printQueue() {

console.log(queue.map((item) => item[0]));

}

```

In this implementation, the `pq` function adds an element to the queue while maintaining the priority order. The `dequeue` function removes and returns the front element of the queue, and the `printQueue` function prints all elements in the queue without removing them.

**Example Usage**

Here's an example usage of the priority queue implementation:

```javascript

const queue = [];

pq([1, 5]);

pq([2, 3]);

pq([3, 5]); // same priority, so order is preserved

printQueue(); // prints: [1, 2]

dequeue();

printQueue(); // prints: [2, 3]

```

In this example, we create an empty queue and enqueue three elements with different priorities. We then print the entire queue to see the order of the elements based on their priority. Finally, we dequeue an element from the front of the queue and print it again to demonstrate that the remaining elements are in the correct order.

Overall, queues provide a fundamental data structure for implementing algorithms and solving problems in programming. By understanding how to create and work with queues, developers can build efficient and effective solutions to a wide range of applications.

"WEBVTTKind: captionsLanguage: enthe q data structure is a way to hold data it's similar to a stack while a stack is first in last out a queue is first in first out an example in real life is when you were waiting in line to buy something at a store the first person to get in the line is the first person to get to the cash register another example is a print queue when a lot of people are printing documents at the same printer the documents are printed in the order they were sent to the print queue in javascript just like a stack you can implement a cue with just an array if you want to limit an array to just the traditional q methods you must create it yourself let me show you one such implementation so we have the queue right here and we're going to have a collection that's going to collect all the items in the queue and this is just kind of a helper function to print or to console.log the collection and here are the main main methods of a queue we have enqueue which is going to push the first item onto the queue and then we have dq which is going to take an item off the queue so there's two ways to do it with an array items can go into the array at the beginning of the array or items can go in the array at the end of the array in this implementation items are going into the array at the end of the array and then they come off of the array at the beginning of the array to put an item onto the queue we're just going to push that item that element onto the queue then to dq we're going to use um the array.shift dot shift just pulls off the first item of the array it removes the first item of the array and returns it another q method is front this is just going to return what item is at the front of the array without removing the item off of the array so we're just going to do collection just going to return what items at the at the zero index of the correct collection array and size we just try to figure out the size of the queue pretty straightforward just collection.length and then is empty check if it's empty uh if there's no items on the queue so let's see how that was going to work down here i'm just going to uncomment that and run the code so we enqueue we created a new queue then we and we enqueued abc so the line the end of the line is the end of the array the beginning of the line is the beginning of the array so it's going to print a b c here and then dq means that the the item at the beginning of the array is going to be removed so the a is going to be removed and then we're going to do um q dot front which i forgot to put the console.log here if i run that again you'll see that it's going to check what what elements at the front of the array which is b and they're going to print the array again it's just going to be b and c because we dequeued a another way to create a cue is a priority queue in a priority queue not only do you pass the element into the queue you also pass the priority of the element so if all the priorities are the same number it's going to behave just like a normal cue but when you pass in elements at different priorities the elements that are passed in with a higher priority are sent to the beginning of the queue so all elements with priority five are ahead of elements with priority four but if elements have the same priority it just behaves like a normal queue so let me explain how the priority queue works first let me show you an example of this code down here where we're using the priority queue so we're going to create the priority queue and then we're going to enqueue something and so we're going to pass in an array the first element in the array is the item we want to put on to the priority queue the second thing in the array is the priority so you can see i'm not pushing them on in the same order two three one but if i run this when we the print the collection it's going to print in the order of the priority and just to show another example let me add an item with the same priority as an item we already have and if i run that you can see these two items have the same priority so they're in the queue in the order that they were pushed on to the queue so everything's the same on a priority queue except the enqueue function so in the nq function first we're going to check if the queue is empty if it's empty you're just going to push on the element but if it's not empty you're going to have to check the priorities to see where to put the element on so we're going to create a variable just to check whether we've added the item to the queue or not and it's false it starts at false and now we're going to have to run through each element in the the collection or the queue to check what the priorities are so we have this for loop that's going to run through each item in the collection and we're going to check is the element at index 1 remember the element that we pass into the queue is an array index 0 is the item you want to put into the queue and index one is the priority so is the priority of the element we're passing into the queue less than the priority of the item in the collection that we're checking and see we're using this i from the for loop we're gonna go through and check every item in the collection and we're gonna check the index one which is the priority of that item and then if the priority is less than the item we're going to add that item or the element to the collection array that's what this splice is doing and then we're going to say add it equals true we're going to break out of the the loop here and then we're going to be done except if the element hasn't been added we are going to then push the element to the array and the only thing that's slightly different is this dq method and this the way i did is kind of optional you could return the entire element with the item and the priority or you can do what i did where i just um return the the item without the priority here that's just index zero of this value which is the item that we got off the beginning of the array well those are cues and priority queues thanks for watching don't forget to subscribe and remember use your code for goodthe q data structure is a way to hold data it's similar to a stack while a stack is first in last out a queue is first in first out an example in real life is when you were waiting in line to buy something at a store the first person to get in the line is the first person to get to the cash register another example is a print queue when a lot of people are printing documents at the same printer the documents are printed in the order they were sent to the print queue in javascript just like a stack you can implement a cue with just an array if you want to limit an array to just the traditional q methods you must create it yourself let me show you one such implementation so we have the queue right here and we're going to have a collection that's going to collect all the items in the queue and this is just kind of a helper function to print or to console.log the collection and here are the main main methods of a queue we have enqueue which is going to push the first item onto the queue and then we have dq which is going to take an item off the queue so there's two ways to do it with an array items can go into the array at the beginning of the array or items can go in the array at the end of the array in this implementation items are going into the array at the end of the array and then they come off of the array at the beginning of the array to put an item onto the queue we're just going to push that item that element onto the queue then to dq we're going to use um the array.shift dot shift just pulls off the first item of the array it removes the first item of the array and returns it another q method is front this is just going to return what item is at the front of the array without removing the item off of the array so we're just going to do collection just going to return what items at the at the zero index of the correct collection array and size we just try to figure out the size of the queue pretty straightforward just collection.length and then is empty check if it's empty uh if there's no items on the queue so let's see how that was going to work down here i'm just going to uncomment that and run the code so we enqueue we created a new queue then we and we enqueued abc so the line the end of the line is the end of the array the beginning of the line is the beginning of the array so it's going to print a b c here and then dq means that the the item at the beginning of the array is going to be removed so the a is going to be removed and then we're going to do um q dot front which i forgot to put the console.log here if i run that again you'll see that it's going to check what what elements at the front of the array which is b and they're going to print the array again it's just going to be b and c because we dequeued a another way to create a cue is a priority queue in a priority queue not only do you pass the element into the queue you also pass the priority of the element so if all the priorities are the same number it's going to behave just like a normal cue but when you pass in elements at different priorities the elements that are passed in with a higher priority are sent to the beginning of the queue so all elements with priority five are ahead of elements with priority four but if elements have the same priority it just behaves like a normal queue so let me explain how the priority queue works first let me show you an example of this code down here where we're using the priority queue so we're going to create the priority queue and then we're going to enqueue something and so we're going to pass in an array the first element in the array is the item we want to put on to the priority queue the second thing in the array is the priority so you can see i'm not pushing them on in the same order two three one but if i run this when we the print the collection it's going to print in the order of the priority and just to show another example let me add an item with the same priority as an item we already have and if i run that you can see these two items have the same priority so they're in the queue in the order that they were pushed on to the queue so everything's the same on a priority queue except the enqueue function so in the nq function first we're going to check if the queue is empty if it's empty you're just going to push on the element but if it's not empty you're going to have to check the priorities to see where to put the element on so we're going to create a variable just to check whether we've added the item to the queue or not and it's false it starts at false and now we're going to have to run through each element in the the collection or the queue to check what the priorities are so we have this for loop that's going to run through each item in the collection and we're going to check is the element at index 1 remember the element that we pass into the queue is an array index 0 is the item you want to put into the queue and index one is the priority so is the priority of the element we're passing into the queue less than the priority of the item in the collection that we're checking and see we're using this i from the for loop we're gonna go through and check every item in the collection and we're gonna check the index one which is the priority of that item and then if the priority is less than the item we're going to add that item or the element to the collection array that's what this splice is doing and then we're going to say add it equals true we're going to break out of the the loop here and then we're going to be done except if the element hasn't been added we are going to then push the element to the array and the only thing that's slightly different is this dq method and this the way i did is kind of optional you could return the entire element with the item and the priority or you can do what i did where i just um return the the item without the priority here that's just index zero of this value which is the item that we got off the beginning of the array well those are cues and priority queues thanks for watching don't forget to subscribe and remember use your code for good\n"