0% found this document useful (0 votes)
7 views21 pages

Ds Ans 2

The document outlines the differences between linear and non-linear data structures, defining linear structures as sequentially arranged and non-linear structures as hierarchical or interconnected. It also explains the concept of Abstract Data Types (ADTs), detailing various operations associated with different ADTs such as List, Stack, Queue, and others. Additionally, it provides algorithms for stack operations, including insertion and deletion, while highlighting the applications of stacks in programming.

Uploaded by

amitsahania399
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views21 pages

Ds Ans 2

The document outlines the differences between linear and non-linear data structures, defining linear structures as sequentially arranged and non-linear structures as hierarchical or interconnected. It also explains the concept of Abstract Data Types (ADTs), detailing various operations associated with different ADTs such as List, Stack, Queue, and others. Additionally, it provides algorithms for stack operations, including insertion and deletion, while highlighting the applications of stacks in programming.

Uploaded by

amitsahania399
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

1.

differentiate between linear and non linear data structure

Ans: Difference Between Linear and Non-Linear Data Structures

Feature Linear Data Structure Non-Linear Data Structure


Elements are arranged Elements are arranged in a hierarchical
Definition
sequentially (one after another). or interconnected manner.
Stored in contiguous memory
locations (e.g., arrays) or Stored in non-contiguous memory
Storage
linked sequentially (e.g., locations (e.g., trees, graphs).
linked lists).
Requires traversal from start to
Can be accessed directly or through
Data Access
end (one-by-one). multiple paths.
Easier to implement and More complex due to multiple
Complexity
understand. connections.
- Trees (Binary Tree, BST, AVL, etc.)
- Arrays - Linked Lists - Stacks
Examples - Graphs (Directed, Undirected,
- Queues
Weighted, etc.) - Heaps
Uses loops (for, while) or Uses recursion, BFS (Breadth-First
Traversal
recursion (for linked lists). Search), DFS (Depth-First Search).
Can be implemented using Requires nodes and pointers for
Implementation
arrays or pointers. hierarchical representation.
Every element has a single
Relationship direct successor and Each element may be connected to
Between Elements predecessor (except first & last multiple elements in different ways.
elements).
- Hierarchical data representation (file
- Simple data storage - CPU
systems) - Network routing (graphs) -
Example Use Cases scheduling (queues) -
AI and game development (decision
Expression evaluation (stacks)
trees)

Summary

 Linear Data Structures → Single level of elements (e.g., Array, Stack, Queue).
 Non-Linear Data Structures → Multiple levels or interconnections (e.g., Tree,
Graph).

2. define abstract data type

Ans: An Abstract Data Type (ADT) is a logical description of a data structure that defines the
operations that can be performed on it, without specifying how these operations are implemented.

Common Examples of ADTs

1. List – Operations: Insert, Delete, Search


2. Stack – Operations: Push, Pop, Peek
3. Queue – Operations: Enqueue, Dequeue, Front
4. Priority Queue – Operations: Insert, Delete Highest/Lowest Priority
5.  Set – Operations: Union, Intersection, Difference
6.  Map (Dictionary) – Operations: Insert(Key, Value), Get(Key), Delete(Key)

3.various operations list of abstract data type

1. List ADT

Operations on Abstract Data Types (ADT)

Abstract Data Types (ADTs) define a set of operations that can be performed on them,
without specifying the internal implementation. Below are the common ADT operations
along with examples:

1. List ADT

A List is an ordered collection of elements where duplicate elements are allowed.

Operations

1. Insert(x, pos) – Insert element x at position pos.


2. Delete(pos) – Remove element at position pos.
3. Find(x) – Check if element x exists in the list.
4. Retrieve(pos) – Get the element at position pos.
5. Size() – Get the total number of elements in the list.

2. Stack ADT (LIFO - Last In, First Out)

A Stack follows the LIFO principle (Last-In, First-Out), meaning elements are added and
removed from the top.

Operations

1. Push(x) – Add element x to the top.


2. Pop() – Remove and return the top element.
3. Peek() – Get the top element without removing it.
4. isEmpty() – Check if the stack is empty.
5. isFull() – Check if the stack is full (in case of an array implementation).

3. Queue ADT (FIFO - First In, First Out)

A Queue follows the FIFO principle, meaning elements are added at the rear and removed
from the front.
Operations

1. Enqueue(x) – Insert element x at the rear.


2. Dequeue() – Remove and return the front element.
3. Front() – Get the front element without removing it.
4. isEmpty() – Check if the queue is empty.
5. isFull() – Check if the queue is full (in case of an array implementation).

4. Deque (Double-Ended Queue) ADT

A Deque allows insertions and deletions from both ends.

Operations

1. InsertFront(x) – Add x at the front.


2. InsertRear(x) – Add x at the rear.
3. DeleteFront() – Remove from the front.
4. DeleteRear() – Remove from the rear.
5. Front() – Get the front element.
6. Rear() – Get the rear element.
7. isEmpty() – Check if the deque is empty.

5. Priority Queue ADT

A Priority Queue is a queue where elements are removed based on priority rather than order
of insertion.

Operations

1. Insert(x, priority) – Insert element x with a given priority.


2. DeleteMax() – Remove the element with the highest priority (Max-Priority Queue).
3. DeleteMin() – Remove the element with the lowest priority (Min-Priority Queue).
4. Peek() – Get the element with the highest priority.

6. Set ADT

A Set is a collection of unique elements (no duplicates).

Operations

1. Insert(x) – Add x to the set.


2. Delete(x) – Remove x from the set.
3. Find(x) – Check if x exists in the set.
4. Union(A, B) – Get elements from both sets A and B.
5. Intersection(A, B) – Get common elements from sets A and B.
6. Difference(A, B) – Get elements in A but not in B.

7. Map (Dictionary) ADT

A Map (or Dictionary) stores key-value pairs.

Operations

1. Insert(Key, Value) – Add a key-value pair.


2. Delete(Key) – Remove the entry for the given key.
3. Find(Key) – Retrieve the value associated with a key.
4. Size() – Get the number of key-value pairs.
5. isEmpty() – Check if the map is empty.

8. Graph ADT

A Graph represents a set of nodes (vertices) and edges.

Operations

1. AddVertex(v) – Add a new vertex v.


2. RemoveVertex(v) – Remove vertex v.
3. AddEdge(v1, v2) – Add an edge between vertices v1 and v2.
4. RemoveEdge(v1, v2) – Remove the edge between v1 and v2.
5. isAdjacent(v1, v2) – Check if v1 and v2 are connected.
6. BFS(v) – Perform Breadth-First Search from vertex v.
7. DFS(v) – Perform Depth-First Search from vertex v.

Summary Table: ADT Operations

ADT Common Operations

List Insert, Delete, Find, Retrieve, Size

Stack Push, Pop, Peek, isEmpty, isFull

Queue Enqueue, Dequeue, Front, isEmpty, isFull

Deque InsertFront, InsertRear, DeleteFront, DeleteRear

Priority Queue Insert, DeleteMax/DeleteMin, Peek

Set Insert, Delete, Find, Union, Intersection, Difference


ADT Common Operations

Map (Dictionary) Insert(Key, Value), Delete(Key), Find(Key), Size

Graph AddVertex, RemoveVertex, AddEdge, RemoveEdge, BFS, DFS

Would you like C implementations for any of these? 😊

4.Define stack

A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle,
meaning the last element added to the stack is the first one to be removed.

Characteristics of a Stack

1. LIFO Order – The last element inserted is the first to be removed.


2. Restricted Access – Elements can only be added or removed from the top of the
stack.
3. Fixed or Dynamic Size – Can be implemented using arrays (fixed size) or linked lists
(dynamic size).

5.operations of stack

Basic Stack Operations

1. Push(x) – Adds element x to the top of the stack.


2. Pop() – Removes and returns the top element.
3. Peek() / Top() – Returns the top element without removing it.
4. isEmpty() – Checks if the stack is empty.
5. isFull() – Checks if the stack is full (only for array implementation).
6. applications of stack

Applications of Stack

A stack is a LIFO (Last In, First Out) data structure widely used in programming and
computing. Below are some key applications of stacks:

1. Expression Evaluation & Conversion

✅ Postfix, Prefix, and Infix Expression Evaluation


 Stacks are used to evaluate mathematical expressions and convert them between infix,
postfix, and prefix notations.
 Example: Converting (A + B) * C (infix) → A B + C * (postfix).
 Used in compilers and interpreters.

2. Function Call Management (Recursion & System Stack)

✅ Handling Function Calls (Call Stack in Programming Languages)

 When a function is called, the return address and local variables are pushed onto
the stack.
 When the function finishes, its data is popped from the stack.
 Example: In recursive function calls, each function call is stacked until the base case
is reached.

🔹 Example of Recursive Stack in C:

void recursiveFunction(int n) {
if (n == 0) return;
printf("Calling %d\n", n);
recursiveFunction(n - 1);
}

 Each recursive call is pushed onto the stack until n == 0, then calls are popped.

3. Undo/Redo Operations in Editors

✅ Text Editors (Undo/Redo Feature)

 Undo (Ctrl + Z) → Push changes onto the stack.


 Redo (Ctrl + Y) → Pop from the undo stack and push onto a redo stack.
 Used in Microsoft Word, Photoshop, and IDEs.

4. Browser History (Back/Forward Navigation)

✅ Back and Forward Navigation in Web Browsers

 Back Button: When a user visits a page, it is pushed onto a stack. Clicking "Back"
pops the last visited page.
 Forward Button: The popped page is pushed onto another stack.

🔹 Example

User visits: A → B → C
Click "Back" → C is popped → User is on B
Click "Forward" → C is pushed back → User is on C

5. Balanced Parentheses & Syntax Checking

✅ Checking Valid Parentheses in Expressions

 Used in compilers to check balanced brackets, e.g., {[()]} is valid, but {[)]} is
not.

🔹 Example (C Code to Check Balanced Parentheses):

#include <stdio.h>
#include <stdbool.h>
#define MAX 100

char stack[MAX];
int top = -1;

void push(char c) { stack[++top] = c; }


char pop() { return (top == -1) ? '\0' : stack[top--]; }

bool isBalanced(char expr[]) {


for (int i = 0; expr[i] != '\0'; i++) {
if (expr[i] == '(' || expr[i] == '{' || expr[i] == '[')
push(expr[i]);
else if (expr[i] == ')' || expr[i] == '}' || expr[i] == ']') {
char popped = pop();
if ((expr[i] == ')' && popped != '(') ||
(expr[i] == '}' && popped != '{') ||
(expr[i] == ']' && popped != '['))
return false;
}
}
return (top == -1);
}

int main() {
char expr[] = "{[()]}";
printf(isBalanced(expr) ? "Balanced\n" : "Not Balanced\n");
}

6. Depth-First Search (DFS) in Graphs & Trees

✅ Graph Traversal (DFS Algorithm)

 Used in graph algorithms like Depth-First Search (DFS), where nodes are pushed
and popped.

7. Memory Management in Operating Systems

✅ Stack-Based Memory Allocation


 Local variables and function calls are managed using a stack in memory.
 Example: Stack Overflow occurs when recursive function calls exceed the stack
limit.

8. Backtracking (Solving Puzzles & Games)

✅ Solving Mazes, Sudoku, and N-Queens Problem

 Backtracking uses a stack to explore possible solutions. If a wrong path is taken, the
stack pops back to the previous step.

🔹 Example:

 In a maze-solving algorithm, the stack keeps track of the path. If a dead-end is


reached, it pops back to the last decision point.

9. Expression Evaluation using Postfix Notation

✅ Evaluating Postfix Expressions Using a Stack

 Example:
 Postfix: 5 3 + 8 * → (5 + 3) * 8 = 64
 The stack stores numbers and operators to compute the result.

🔹 Example (Postfix Evaluation in C)

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX 100


int stack[MAX], top = -1;

void push(int num) { stack[++top] = num; }


int pop() { return stack[top--]; }

int evaluatePostfix(char* expr) {


for (int i = 0; expr[i] != '\0'; i++) {
if (isdigit(expr[i]))
push(expr[i] - '0'); // Convert char to int
else {
int val2 = pop(), val1 = pop();
switch (expr[i]) {
case '+': push(val1 + val2); break;
case '-': push(val1 - val2); break;
case '*': push(val1 * val2); break;
case '/': push(val1 / val2); break;
}
}
}
return pop();
}

int main() {
char expr[] = "53+8*";
printf("Result: %d\n", evaluatePostfix(expr)); // Output: 64
}

10. Undo Feature in Software Applications

✅ Stack Helps Store Previous Actions in Software

 Used in photo editing apps, text editors, and design tools.

Summary Table: Applications of Stack

Application Description
Expression Evaluation Converts and evaluates infix, prefix, and postfix expressions.
Function Call Stack Manages function calls and recursion.
Undo/Redo Operations Used in text editors, graphics software, and word processors.
Browser History Tracks visited web pages using a back-and-forward system.
Balanced Parentheses Checks if expressions have correct {}, [], ().
Graph Traversal (DFS) Uses stack-based depth-first search.
Memory Management Used in stack-based memory allocation.
Backtracking Solves problems like mazes, Sudoku, and puzzles.
Postfix Evaluation Evaluates mathematical expressions efficiently.

Final Thoughts

Stacks are powerful and versatile data structures used in algorithms, system design, and
real-world applications like compilers, operating systems, and games.

Would you like a specific implementation in C for any of these applications? 😊

9. elaborate an algorithm to insert and delete an element from stack

Stack Operations: Push & Pop Algorithm

A stack follows the LIFO (Last In, First Out) principle, meaning the last inserted element
is the first to be removed.

Below are the algorithms for inserting (Push) and deleting (Pop) an element from a stack
using an array implementation.
1. PUSH Operation (Insertion into Stack)

Definition: The Push operation adds an element to the top of the stack.

Algorithm: Push (Insert into Stack)

Step-by-Step Process

1. Check Overflow:
o If top == MAX - 1, the stack is full (Overflow Condition).
2. Increment Top:
o Increase top by 1 to point to the next position.
3. Insert Element:
o Assign stack[top] = value.
4. End Operation.

Algorithm (Pseudocode)
PUSH(stack, top, MAX, value)
1. IF top == MAX - 1 THEN
PRINT "Stack Overflow"
RETURN
2. top = top + 1
3. stack[top] = value
4. PRINT "Element Pushed"
5. RETURN

Example Execution

Initial Stack (Empty)


Top → -1 (Stack is empty)
Push(10)
Top → 0
Stack: | 10 |
Push(20)
Top → 1
Stack: | 20 |
| 10 |
Push(30)
Top → 2
Stack: | 30 |
| 20 |
| 10 |

2. POP Operation (Deletion from Stack)

Definition: The Pop operation removes an element from the top of the stack.
Algorithm: Pop (Delete from Stack)

Step-by-Step Process

1. Check Underflow:
o If top == -1, the stack is empty (Underflow Condition).
2. Retrieve Element:
o Store stack[top] in a variable.
3. Decrease Top:
o Reduce top by 1 to remove the element.
4. Return the Removed Element.

Algorithm (Pseudocode)
POP(stack, top)
1. IF top == -1 THEN
PRINT "Stack Underflow"
RETURN NULL
2. element = stack[top]
3. top = top - 1
4. RETURN element

Example Execution

Initial Stack
Top → 2
Stack: | 30 | <-- Top
| 20 |
| 10 |
Pop() → Removes 30
Top → 1
Stack: | 20 | <-- New Top
| 10 |
Pop() → Removes 20
Top → 0
Stack: | 10 |
Pop() → Removes 10
Top → -1 (Stack is Empty)
Pop() → Stack Underflow!
Error: Stack is Empty (Underflow)

3. C Program for Stack Operations


#include <stdio.h>
#include <stdlib.h>

#define MAX 5 // Define maximum stack size

typedef struct {
int items[MAX];
int top;
} Stack;

// Initialize Stack
void init(Stack *s) {
s->top = -1;
}

// Check if Stack is Empty


int isEmpty(Stack *s) {
return s->top == -1;
}

// Check if Stack is Full


int isFull(Stack *s) {
return s->top == MAX - 1;
}

// Push Operation (Insert)


void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack Overflow! Cannot push %d\n", value);
return;
}
s->items[++s->top] = value;
printf("Pushed: %d\n", value);
}

// Pop Operation (Delete)


int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack Underflow! Cannot pop.\n");
return -1;
}
return s->items[s->top--];
}

// Peek Operation (Get Top Element)


int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is Empty!\n");
return -1;
}
return s->items[s->top];
}

// Main Function
int main() {
Stack s;
init(&s);

push(&s, 10);
push(&s, 20);
push(&s, 30);

printf("Top Element: %d\n", peek(&s));

printf("Popped: %d\n", pop(&s));


printf("Popped: %d\n", pop(&s));
printf("Popped: %d\n", pop(&s));

// Trying to pop from an empty stack


pop(&s);

return 0;
}

4. Output of the Above Program


Pushed: 10
Pushed: 20
Pushed: 30
Top Element: 30
Popped: 30
Popped: 20
Popped: 10
Stack Underflow! Cannot pop.

5. Time Complexity Analysis


Operation Time Complexity

Push() O(1)

Pop() O(1)

Peek() O(1)

Each operation in a stack runs in constant time O(1), making it an efficient data structure.

6. Conclusion

 The Push operation adds an element at the top of the stack.


 The Pop operation removes the topmost element from the stack.
 Stack operations are used in function calls, undo/redo, DFS, and expression evaluation.

Would you like a linked list-based stack implementation as well? 😊

10.define queueu

A queue is a linear data structure that follows the FIFO (First In, First Out) principle,
meaning the element inserted first is removed first.

11. operations of queue

Basic Queue Operations

1. Enqueue(x) – Inserts element x at the rear.


2. Dequeue() – Removes and returns the element from the front.
3. Peek() / Front() – Returns the front element without removing it.
4. isEmpty() – Checks if the queue is empty.
5. isFull() – Checks if the queue is full (only for fixed-size arrays).
12.types of queue

1. Simple Queue – Follows FIFO, insertion at rear, deletion from front.


2. Circular Queue – The rear connects back to the front to utilize memory efficiently.
3. Priority Queue – Elements are dequeued based on priority, not order.
4. Deque (Double-Ended Queue) – Insertions and deletions happen from both ends.

13. elaborate an algorithm to insert and delete an element from queue

1. Algorithm for Insertion (Enqueue) in a Queue

Objective: Insert an element at the rear end of the queue.

🔹 Algorithm (Enqueue Operation)

1. Check if the queue is full


o If (rear == size - 1), print "Queue Overflow" and exit.
2. Increment the rear pointer
o rear = rear + 1
3. Insert the new element at queue[rear].
4. If inserting the first element, update front = 0 to indicate the queue is no longer empty.
5. End of the operation.

🔹 Pseudocode for Enqueue:

plaintext
CopyEdit
Enqueue(queue, item):
IF rear == size - 1 THEN
PRINT "Queue Overflow"
RETURN
END IF
IF front == -1 THEN // First element insertion
front = 0
END IF
rear = rear + 1
queue[rear] = item
PRINT "Element Inserted"
END

2. Algorithm for Deletion (Dequeue) from a Queue

Objective: Remove an element from the front end of the queue.

🔹 Algorithm (Dequeue Operation)

1. Check if the queue is empty


o If front == -1 OR front > rear, print "Queue Underflow" and exit.
2. Retrieve the front element from queue[front].
3. Increment the front pointer
o front = front + 1
4. If all elements are deleted (front > rear), reset front = -1 and rear = -1.
5. End of the operation

14.circular queue

A Circular Queue is a linear data structure that follows the FIFO (First In, First Out)
principle but connects the last position back to the first position to form a circular
arrangement.

This eliminates the problem of wasted space in a regular queue when elements are dequeued.

. Enqueue Algorithm

1. Check if the queue is full:


o If (rear + 1) % size == front, print "Queue Overflow" and return.
2. If queue is empty (front == -1), set front = 0.
3. Move rear to the next position using:
o rear = (rear + 1) % size
4. Insert the new element at queue[rear].

2. Dequeue Algorithm

1. Check if the queue is empty:


o If front == -1, print "Queue Underflow" and return.
2. Retrieve and remove the front element.
3. If only one element was in the queue, reset front = -1 and rear = -1.
4. Otherwise, move front to the next position using:
o front = (front + 1) % size.

14.distinguish between stack and queue

Difference Between Stack and Queue

Feature Stack Queue


A stack is a linear data structure that
A queue is a linear data structure
Definition follows the LIFO (Last In, First Out) that follows the FIFO (First In,
principle. First Out) principle.
LIFO (Last In, First Out) - The last FIFO (First In, First Out) - The
Basic Principle element inserted is the first to be first element inserted is the first to
removed. be removed.
- Enqueue (Insert at rear) -
- Push (Insert) - Pop (Remove) - Peek
Operations Dequeue (Remove from front) -
(Top element)
Peek (Front element)
Feature Stack Queue
Insertion & Both operations take place at the same Insertion occurs at the rear, and
Deletion end (top). deletion occurs at the front.
Used in problems that require
Used in problems that require
Use Case ordering and processing items
reversing or backtracking.
sequentially.
Can be implemented using an
Can be implemented using an array or
Implementation array, linked list, or circular
linked list.
queue.
- Undo/Redo in text editors -
- CPU Scheduling - Print queue -
Examples Backtracking (e.g., solving mazes) -
Handling requests in a web server
Function call stack in programming

15.

Ans:

Priority Queue: Definition, Diagram, and Operations


Definition of Priority Queue

A priority queue is a special type of queue where each element is assigned a priority. The
element with the highest priority is dequeued (removed) first, regardless of the order in
which it was enqueued.

 If two elements have the same priority, they follow the FIFO (First-In, First-Out) order.
 A priority queue can be implemented using an array, linked list, binary heap, or balanced
tree.

Diagram of a Priority Queue

Here is an example of a priority queue with different elements and their assigned priorities:

Priority Queue
+----+--------+------------+
| No | Item | Priority |
+----+--------+------------+
| 1 | TaskA | 3 |
| 2 | TaskB | 1 |
| 3 | TaskC | 4 |
| 4 | TaskD | 2 |
+----+--------+------------+

Dequeuing follows priority order: TaskC → TaskA → TaskD → TaskB


📌 Priority Order (Highest to Lowest): TaskC (4) → TaskA (3) → TaskD (2) → TaskB
(1)
📌 Not FIFO, but priority-based order.

Operations on a Priority Queue

A priority queue supports the following operations:

1. Insertion (Enqueue with Priority)


o Insert an element along with its priority.
o The queue maintains the order based on priority.

2. Deletion (Dequeue Highest Priority)


o Remove the element with the highest priority.

3. Peek (Get Highest Priority Element)


o Return the element with the highest priority without removing it.

4. Check if the Queue is Empty


o Returns true if no elements exist.

5. Check if the Queue is Full (For Fixed Size)


o Returns true if the queue is full.

Implementation Methods

Priority queues can be implemented using:

1. Unsorted Array → Insert at the end, find the highest priority during dequeue (O(n)).
2. Sorted Array → Insert in sorted order (O(n)), dequeue in O(1).
3. Linked List → Similar to arrays but with dynamic memory allocation.
4. Binary Heap (Efficient) → Insert and remove in O(log n) time.

C Implementation of Priority Queue (Using Array)


#include <stdio.h>

#define SIZE 5

struct PriorityQueue {
int item;
int priority;
} queue[SIZE];

int count = 0;

// Function to insert an element into the priority queue


void enqueue(int item, int priority) {
if (count == SIZE) {
printf("Queue is full! Cannot insert %d\n", item);
return;
}

int i = count - 1;
// Insert in sorted order (Descending priority)
while (i >= 0 && queue[i].priority < priority) {
queue[i + 1] = queue[i];
i--;
}

queue[i + 1].item = item;


queue[i + 1].priority = priority;
count++;

printf("Inserted %d with priority %d\n", item, priority);


}

// Function to remove the highest priority element


void dequeue() {
if (count == 0) {
printf("Queue is empty! Cannot dequeue\n");
return;
}

printf("Removed %d with priority %d\n", queue[0].item,


queue[0].priority);

// Shift elements to maintain order


for (int i = 0; i < count - 1; i++) {
queue[i] = queue[i + 1];
}
count--;
}

// Function to display the priority queue


void display() {
if (count == 0) {
printf("Queue is empty!\n");
return;
}
printf("Priority Queue: \n");
for (int i = 0; i < count; i++) {
printf("%d (Priority: %d)\n", queue[i].item, queue[i].priority);
}
}

// Main function to test priority queue operations


int main() {
enqueue(10, 2);
enqueue(20, 1);
enqueue(30, 4);
enqueue(40, 3);
enqueue(50, 5);

display();

dequeue();
display();

enqueue(60, 4);
display();

return 0;
}

q. application of priority queue

ans: Applications of Priority Queue

A priority queue is widely used in real-world applications where elements must be


processed based on priority rather than arrival order (FIFO). Below are some key
applications:

1. CPU Scheduling (Operating Systems)

📌 How it works:

 In modern operating systems, multiple processes run simultaneously.


 Each process is assigned a priority (higher priority processes execute first).
 Example: Shortest Job Next (SJN), Priority Scheduling.
🖥 Real-world example: Windows, Linux process scheduling.

2. Dijkstra’s Algorithm (Shortest Path in Graphs)

📌 How it works:

 Used in network routing and Google Maps.


 The priority queue stores graph nodes with the shortest known distance.
 The node with the smallest distance (highest priority) is processed first.
🗺 Real-world example: Google Maps, GPS navigation.

3. Network Packet Scheduling

📌 How it works:

 In computer networks, data packets are transmitted based on priority.


 High-priority packets (like video calls) are sent before lower-priority packets (like
emails).
📡 Real-world example: Internet traffic management, VoIP (Skype, Zoom).

4. Emergency Room Scheduling (Healthcare)


📌 How it works:

 In hospitals, critical patients are treated first, even if others arrived earlier.
 Example: A heart attack patient is treated before a minor injury.
🏥 Real-world example: Hospital emergency departments.

5. Data Compression (Huffman Coding)

📌 How it works:

 Used in file compression algorithms like ZIP and JPEG.


 Characters with higher frequency (priority) are encoded with shorter binary codes.
📂 Real-world example: WinRAR, PNG, MP3 compression.

6. AI and Machine Learning (Task Scheduling)

📌 How it works:

 In AI systems, tasks are executed based on importance (priority).


 A self-driving car assigns higher priority to obstacles directly in front than those
far away.
🚗 Real-world example: Tesla autopilot, AI bots.

7. Stock Market Order Matching

📌 How it works:

 In stock trading, high-priority orders (large volume, high price) are processed first.
 Buy/sell orders are queued based on priority.
📈 Real-world example: New York Stock Exchange (NYSE), Nasdaq.

8. Airline Reservation Systems

📌 How it works:

 Higher priority is given to business class and frequent flyers over economy
passengers.
 Airline booking systems maintain a priority queue for ticket upgrades and waiting
lists.
✈ Real-world example: Delta, Emirates airline reservations.
9. Operating System Interrupt Handling

📌 How it works:

 When multiple hardware interrupts occur, high-priority interrupts (e.g., hardware


failure) are handled before lower-priority ones (e.g., mouse click).
⚡ Real-world example: Windows, Linux, embedded systems.

10. Printer Job Scheduling

📌 How it works:

 In office printers, documents are queued with priority levels (urgent documents print
first).
🖨 Real-world example: Office printer queues.

You might also like