Enqueue PriorityQueue nghĩa là thêm phần tử theo thứ tự priority. Coi số lớn = priority cao. Duyệt container đến khi thấy priority thấp hơn thì chèn vào đó. Nếu không, push cuối.
Tạo element object với data và priority. Triển khai enqueue:
Ví dụ
enqueue(data, priority) { if (this.isFull()) { console.log("Queue Overflow!"); return; } let currElem = new this.Element(data, priority); let addedFlag = false; for(let i = 0; i < this.container.length; i ++) { if(currElem.priority < this.container[i].priority) { this.container.splice(i, 0, currElem); addedFlag = true; break; } } if (!addedFlag) { this.container.push(currElem); } }
Kiểm tra:
Ví dụ
let q = new PriorityQueue(4); q.enqueue("Hello", 3); q.enqueue("World", 2); q.enqueue("Foo", 8); q.display();
Kết quả
[ { data: 'World', priority: 2 }, { data: 'Hello', priority: 3 }, { data: 'Foo', priority: 8 } ]
Phần tử tự sắp xếp theo priority tăng dần (cao nhất ở cuối). Enqueue hoạt động như insertion sort.