ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Data Structures
    COMP2117
    Progress0 / 37 topics
    Topics
    1. Abstract Data Types2. Complexity Analysis3. Big Oh Notation4. Stacks (Linked Lists and Array Implementations)5. Recursion and analyzing recursive algorithms6. Divide and Conquer Algorithms7. Sorting Algorithms8. Selection Sort9. Insertion Sort10. Merge Sort11. Quick Sort12. Bubble Sort13. Heap Sort14. Shell Sort15. Radix Sort16. Bucket Sort17. Queue18. Dequeuer19. Priority Queues (linked and array implementations of queues)20. Linked List and Its Various Types21. Sorted Linked List22. Searching an Unsorted Array23. Binary Search for Sorted Arrays24. Hashing and Indexing25. Open Addressing and Chaining26. Trees and Tree Traversals27. Binary Search Trees28. Heaps29. M-Way Trees30. Balanced Trees31. Graphs32. Breadth-First Traversal33. Depth-First Traversal34. Topological Order35. Shortest Path36. Adjacency Matrix and Adjacency List Implementations37. Memory Management and Garbage Collection
    COMP2117›Priority Queues (linked and array implementations of queues)
    Data StructuresTopic 19 of 37

    Priority Queues (linked and array implementations of queues)

    5 minread
    920words
    Intermediatelevel

    Priority Queue

    A priority queue is an abstract data structure where each element has a priority associated with it. Elements are dequeued based on their priority rather than their order of insertion. In some cases, if two elements have the same priority, they follow the First In, First Out (FIFO) order, like a regular queue.

    Key Operations:

    1. Insert: Add an element with a priority.
    2. Delete (Dequeue): Remove and return the element with the highest priority.
    3. Peek/Top: Return the element with the highest priority without removing it.

    Priority Queue Types:

    1. Max Priority Queue: The element with the highest priority is dequeued first.
    2. Min Priority Queue: The element with the lowest priority is dequeued first.

    Priority Queue Implementations

    There are two common ways to implement a priority queue: using arrays and linked lists.


    1. Priority Queue Using Arrays

    In the array-based implementation, elements are stored in an array, and the priority is managed by comparing values or using an auxiliary array for priorities.

    C++ Code (Array Implementation):

    #include <iostream>
    using namespace std;
    
    class PriorityQueue {
        int arr[5];    // Array to store elements
        int priority[5];  // Array to store priorities
        int size;
    
    public:
        PriorityQueue() {
            size = 0;
        }
    
        // Function to insert an element with a priority
        void insert(int value, int pri) {
            if (size == 5) {
                cout << "Queue is full!\n";
                return;
            }
    
            arr[size] = value;
            priority[size] = pri;
            size++;
            cout << value << " inserted with priority " << pri << endl;
        }
    
        // Function to delete the highest priority element
        void deleteHighestPriority() {
            if (size == 0) {
                cout << "Queue is empty!\n";
                return;
            }
    
            int maxPriorityIdx = 0;
            for (int i = 1; i < size; i++) {
                if (priority[i] > priority[maxPriorityIdx]) {
                    maxPriorityIdx = i;
                }
            }
    
            cout << "Element with value " << arr[maxPriorityIdx] << " and highest priority " << priority[maxPriorityIdx] << " dequeued.\n";
    
            // Shift elements
            for (int i = maxPriorityIdx; i < size - 1; i++) {
                arr[i] = arr[i + 1];
                priority[i] = priority[i + 1];
            }
    
            size--;
        }
    
        // Function to peek the highest priority element
        int peekHighestPriority() {
            if (size == 0) return -1;
    
            int maxPriorityIdx = 0;
            for (int i = 1; i < size; i++) {
                if (priority[i] > priority[maxPriorityIdx]) {
                    maxPriorityIdx = i;
                }
            }
    
            return arr[maxPriorityIdx];
        }
    };
    
    int main() {
        PriorityQueue pq;
        pq.insert(10, 2);
        pq.insert(20, 5);
        pq.insert(30, 1);
        cout << "Highest priority element: " << pq.peekHighestPriority() << endl;
        pq.deleteHighestPriority();
        pq.deleteHighestPriority();
        return 0;
    }
    

    Time Complexity (Array-based Priority Queue):

    • Insert: O(1) (simply appending the element to the end).
    • Delete (Dequeue): O(n) (linear search for the highest priority).
    • Peek: O(n) (linear search for the highest priority).

    2. Priority Queue Using Linked List

    In the linked list-based implementation, each node contains both the value and its priority. The nodes can either be inserted in a sorted order based on priority, or we can search for the highest priority element during dequeuing.

    C++ Code (Linked List Implementation):

    #include <iostream>
    using namespace std;
    
    struct Node {
        int data;
        int priority;
        Node* next;
    };
    
    class PriorityQueue {
        Node* head;
    
    public:
        PriorityQueue() {
            head = NULL;
        }
    
        // Function to insert an element with priority
        void insert(int value, int pri) {
            Node* newNode = new Node();
            newNode->data = value;
            newNode->priority = pri;
            newNode->next = NULL;
    
            if (head == NULL || pri > head->priority) {
                newNode->next = head;
                head = newNode;
            } else {
                Node* temp = head;
                while (temp->next != NULL && temp->next->priority >= pri) {
                    temp = temp->next;
                }
                newNode->next = temp->next;
                temp->next = newNode;
            }
            cout << value << " inserted with priority " << pri << endl;
        }
    
        // Function to delete the highest priority element
        void deleteHighestPriority() {
            if (head == NULL) {
                cout << "Queue is empty!\n";
                return;
            }
    
            Node* temp = head;
            head = head->next;
            cout << "Element with value " << temp->data << " and highest priority " << temp->priority << " dequeued.\n";
            delete temp;
        }
    
        // Function to peek the highest priority element
        int peekHighestPriority() {
            if (head == NULL) return -1;
            return head->data;
        }
    };
    
    int main() {
        PriorityQueue pq;
        pq.insert(10, 2);
        pq.insert(20, 5);
        pq.insert(30, 1);
        cout << "Highest priority element: " << pq.peekHighestPriority() << endl;
        pq.deleteHighestPriority();
        pq.deleteHighestPriority();
        return 0;
    }
    

    Time Complexity (Linked List-based Priority Queue):

    • Insert: O(n) (inserting in a sorted position based on priority).
    • Delete (Dequeue): O(1) (head node always has the highest priority).
    • Peek: O(1) (highest priority is always at the head).

    Comparison: Array vs. Linked List

    Operation Array-Based Queue Linked List-Based Queue
    Insert O(1) O(n)
    Delete (Dequeue) O(n) (search for priority) O(1)
    Peek (Highest Priority) O(n) (search for priority) O(1)
    Space Complexity Fixed size (if using static arrays) Dynamic (no fixed size)

    Conclusion

    • Array-based priority queues are simple to implement and offer fast insertion (O(1)) but are inefficient in dequeuing (O(n)).
    • Linked list-based priority queues allow for faster dequeuing (O(1)) but require more time for insertion (O(n)) when maintaining the priority order.
    Previous topic 18
    Dequeuer
    Next topic 20
    Linked List and Its Various Types

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time5 min
      Word count920
      Code examples0
      DifficultyIntermediate