0% found this document useful (0 votes)
8 views

Module-1

The document provides an overview of data structures, categorizing them into linear and non-linear types, and discusses their importance in organizing and managing data efficiently. It details various data structures such as arrays, stacks, queues, trees, and graphs, along with their implementations and applications. Additionally, the document covers time and space complexity, including asymptotic notations for analyzing algorithm performance.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Module-1

The document provides an overview of data structures, categorizing them into linear and non-linear types, and discusses their importance in organizing and managing data efficiently. It details various data structures such as arrays, stacks, queues, trees, and graphs, along with their implementations and applications. Additionally, the document covers time and space complexity, including asymptotic notations for analyzing algorithm performance.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 125

Introduction Data

Structure
&
Stacks and Queues
MODULE-1
Overview of Data Structures
Data structure is a storage that is used to store and organize data.
It is a way of arranging data on a computer so that it can be accessed and
updated efficiently.
Depending on your requirement and project, it is important to choose the
right data structure for your project.
For example, if you want to store data sequentially in the memory, then you
can go for the Array data structure.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 2


 Basically it deals with the manipulation and organization of data.
 The major advantages of data structures are listed below:
 It provides different levels of organizing data.
 Management of large dataset
 Design of efficient algorithms
Types of Data Structure
Basically, data structures are divided into two categories:

 Linear data structure


 Non-linear data structure

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 3


1. Linear data structures
 In linear data structures, the elements are arranged in sequence one after the other.
 Since elements are arranged in particular order, they are easy to implement.

 However, when the complexity of the program increases, the linear data structures
might not be the best choice because of operational complexities.

Popular linear data structures are:


 Array Data Structure
 Stack Data Structure
 Queue Data Structure
 Linked List Data Structure

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 4


Array

Stack

queue

Linked list

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 5


2. Non linear data structures

 Unlike linear data structures, elements in non-linear data structures are


not in any sequence.
 Instead they are arranged in a hierarchical manner where one element
will be connected to one or more elements.

 Non-linear data structures are further divided into:


 Graph
 Tree based data structures
 Tables
 Sets

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 6


In graph data structure, each node is called vertex and
each vertex is connected to other vertices through edges.

Popular Graph Based Data Structures:

• Spanning Tree and Minimum Spanning Tree


• Strongly Connected Components
• Adjacency Matrix
• Adjacency List

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 7


A tree is also a collection of vertices and edges.
However, in tree data structure, there can only be one edge
between two vertices.

Popular Tree based Data Structure

• Binary Tree
• Binary Search Tree
• AVL Tree
• B-Tree
• B+ Tree
• Red-Black Tree

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 8


Hash Table

 Hashing is a technique that is used to uniquely identify a specific object from


a group of similar objects.

 The Hash table data structure stores elements in key-value pairs where

 Key- unique integer that is used for indexing the values


 Value - data that are associated with keys.

 The idea of hashing is to distribute entries (key/value pairs) uniformly


across an array.
 Each element is assigned a key (converted key).
 By using that key you can access the element.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 9


A set is a data structure that can store any number of unique values in
any order you so wish.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 10


DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 11
Time complexity
Amount of time required for an algorithm for its execution.
Best case Time Complexity – Minimum amount of Time
Worst case Time Complexity – Maximum amount of Time
Average case Time Complexity – Average amount of Time
Approaches:
1. Frequency count or step count
2. Asymptotic notations

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 12


On what basis we could compare the time complexity of the data structures?
◦ Based on operations performed by them.

Example:
Inserting an element at the beginning of the list is faster in Linked list than
Array.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 13


Asymptotic notations

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 14


Inserting an element at the beginning of Array.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 15


If we have 1000 elements in an array?
Therefore, if the size of input is n, then f(n) is a function of n denotes time
complexity.

f(n)=n

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 16


DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 17
DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 18
DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 19
DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 20
DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 21
Asymptotic Notations
Following are the commonly used asymptotic notations to calculate the
running time complexity of an algorithm.

Ο Notation (Big Oh Notation)


Ω Notation (Omega Notation)
θ Notation (Theta Notation)

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 22


Big - Oh Notation (O)
This notation describes the upper bound of the running time for an
algorithm.
Big Oh notation ensures that the function never grows faster than its upper
bound.
Thus, it measures the performance of an algorithm by describing the order of
growth for a function and by giving the least upper bound for that function.
 Big Oh measures the worst-case time complexity for the given algorithm
i.e., it measures the longest time an algorithm can execute.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 23


We are providing an upper bound to f(n)
i.e. For any value of n, the running time of an algorithm does not cross the time
provided by O(g(n)).

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 24


Let f(n) = 3n+2 and g(n) = n.
We need to check whether f(n) = O(g(n)) or not.
For f(n) to be equal to O(g(n)), both the functions f(n) and g(n) must satisfy
the following condition: f(n) ≤ c.g(n).
To check if the condition holds, replace f(n) by 3n+2 and g(n) by n
i.e. 3n+2 <= c.n
Let c=7 and n=1, then 3(1)+2 <= 7*1 ⇒ 5<=7 which is true.
Thus, f(n) <= c.g(n) is true for n=1.
 For n=2, 3(2)+2 <= 7*2 ⇒ 8 <= 14 which is again true.
Therefore, f(n) <=c.g(n) is true for n=2 as well.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 25


From here, we can conclude that f(n) <= c.g(n) holds for all values of n,
given that c=7.
Thus, we can say that the above equation always holds for some constant c
and some constant n0.
So, f(n) is equal to Big Oh of g(n) i.e. f(n) = O(g(n)) or we can say that
c.g(n) is an upper bound on function f(n).

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 26


Big - Omega Notation (Ω)
It is the opposite of Big-Oh notation.
Omega notation always describes the best-case scenario for a particular
algorithm.
Omega represents the lower bound of running time for an algorithm.
It will measure the least amount of time that an algorithm can take for its
execution in the best case.
Computing omega:
1. Let f(n) and g(n) be two functions defined on a set of natural numbers.
2. Then, f(n) = Ω(g(n)) only if the growth of f(n) is faster than the growth of
g(n).
3. Mathematically, its equation will be f(n) ≥ c.g(n) where c and n0 are constants
such that c>0 and n>n0.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 27


1. Let f(n) = 2n+3, g(n) = n, we need to find whether f(n)= Ω (g(n)) or not.
2. For f(n) to be equal to the omega of g(n), it must satisfy the condition:
f(n)≥ c.g(n)
3. Replace f(n) by 2n+3 and g(n) by n. i.e. 2n+3 ≥ c*n
4. Let c=1 i.e. value of constant c=1.
5. For n=1,
2(1) + 3 ≥ 1(1) .⇒ 5 ≥ 1 which is true.
6. Similarly, for n=2,
2(2)+3 ≥ 1(2) ⇒ 7 ≥ 2 which is again true.
7. If we check for further values, the equation holds for every value of n given that
c=1.
The function g(n) is the lower bound of the function f(n) and thus it gives the running
time for the function f(n) in the best possible case.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 28


Big - Theta Notation (Θ)
While Big Oh gives the worst-case analysis and omega gives the best case analysis, theta lies somewhere in
between.
Theta notation gives the average case analysis for a function or algorithm.
 In real-world problems, not every time the algorithm will have either the best or worst-case scenario.
Practically, an algorithm is always performing in some average case i.e. the algorithm keeps on fluctuating.
Computing Theta
1. Let there be two functions: f(n) and g(n) defined on a set of positive integers.
2. Then, f(n) = Θ(g(n)) if
c1.g(n)≤ f(n)≤ c2.g(n) where c1, c2 are constants.
3. In theta notation, two limits bind the function i.e. both the upper limit as well as the lower limit. This is
what makes the theta notation return the average case for an algorithm.
4. Thus, the condition f(n)= θg(n) becomes true only when c1.g(n) is less than or equal to f(n) and c2.g(n) is
greater than or equal to f(n).

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 29


1. Let f(n) = 2n+3 and g(n) = n.

2. Replace f(n) with 2n+3 and g(n) with n in the equation


c1.g(n)≤ f(n)≤ c2.g(n).

Then the equation will be c1.n ≤2n+3≤ c2.n

3. To ensure that the equation holds, let c1=1 and c2=5.

4. Thus, for n=1,


the equation will be 1(1) ≤ 2(1)+3 ≤ 5(1) ⇒ 1 ≤ 5 ≤ 5 which is true.

5. For n=2,
The equation will be 1(2) ≤ 2(2)+3 ≤ 5(2) ⇒ 2 ≤ 7 ≤ 10 which is
again true.

6. Hence, we can say that the equation holds for all the values of n
given that c1=1 and c2=5.

7. Therefore, we can say that for the above example, f(n) is equal to
θ(g(n)). And it gives average-case complexity for f(n).

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 30


Common asymptotic notations
Constant O(1)
Logarithmic O(log n)
Linear O(n)
n log n O(n log n)
Quadratic O(n2)
Cubic O(n3)
Polynomial nO(1)
Exponential 2O(n)

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 31


Time complexity of some most commonly used algorithms
Searching techniques:

Algorithm Worst-case complexity


Linear search O(n)
Binary search O(log n)

Sorting techniques:

Algorithm Worst-case complexity


Insertion sort O(n2)
Selection sort O(n2)
Bubble sort O(n2)
Merge sort O(n logn)
Quicksort O(n2)
Radix sort O(nk)
Bucket sort O(n2)

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 32


Space complexity
Amount of space required for an algorithm for its execution.
For any algorithm, memory is required for the following purposes...
1. To store program instructions.
2. To store constant values.
3. To store variable values.
4. And for few other things like function calls, jumping statements etc,.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 33


when a program is under execution it uses the computer memory for THREE reasons.
1.Instruction Space: It is the amount of memory used to store compiled version of instructions.
2.Environmental Stack: It is the amount of memory used to store information of partially executed functions
at the time of function call.
3.Data Space: It is the amount of memory used to store all the variables and constants.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 34


To calculate the space complexity, we must know the memory required to store different datatype values
(according to the compiler).
 2 or 4 bytes to store Integer value.
 4 bytes to store Floating Point value.
 1 byte to store Character value.
 6 (OR) 8 bytes to store double value.

int square(int a)
{
How many bytes of memory required to store variable ’a’ ?
return a*a;
}

If any algorithm requires a fixed amount of space for all input values then that
space complexity is said to be Constant Space Complexity.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 35


int sum(int A[ ], int n)
{
int sum = 0, i;
for(i = 0; i < n; i++)
sum = sum + A[i];
return sum;
}

If the amount of space required by an algorithm is increased with the increase of
input value, then that space complexity is said to be Linear Space Complexity.

DATA STRUCTURES AND ALGORITHMS (UNIT-1) | CSSE 36


Stacks: Introduction, Definition, Implementation of stacks using arrays,
Implementation of stacks using linked list, Applications of Stacks.

Queues: Introduction, Definition, Implementation of queues using arrays,


Implementation of queues using linked list, Circular Queue, Dequeue, Priority Queue,
Applications of Queues.
Introduction to Stacks
• The stack is based on the LIFO (Last In First Out) principle as the last element
inserted will be on the top of the stack.

• Since deletion is done from the same end, the last element inserted is the first
element to be deleted.

• Apart from initialization, the common operations associated with a stack are push
and pop.

• Inserting an item in a stack is called pushing it onto the stack.

• Removing an item from a stack is called popping the stack.

• Items are added and removed from only one designated end called the top of the
stack.

• Two important preconditions associated with the push and pop operations are
overflow and underflow, respectively.
Implementation of Stack

A stack can be implemented in either of the following two ways:


• Statically using arrays
• Dynamically by linked list
Array Implementation of Stacks
Push an element: push()
top

Array index
1

push(1)
(-1+1=0)
Data to be inserted
push(1)
push(1)
Static final int MAX=10;
int arr[]=new int[MAX];
Int top;
Stack()
{
Top=-1;
}
Boolean push(int x)
{
If(top>=Max-1)
{
sop(overflow);
}
Else
{
Arr[++top]=x;
sop(x +” pushed into the stack”);
Return true;}
}
int pop()
{
if(top <0)
sop(“Stack is Underflow”);
Return 0;
else {
Int x=arr[top--];
return x;
}
}
int Display()
int peek() {
{
for(int i:stack)
if(top <0)
sop(“Stack is Underflow”); { sop(i+” “);
Return 0; }
else { }
Int x=arr[top];
return x;
}
}
Pop an element: pop()

5-1=4
# import java.util.*; int pop()
class Stack {
{ if (top < 0)
static final int MAX=1000; {
int top; System.out.println("Stack Underflow");
int a[] = new int[MAX]; return 0;
boolean isEmpty() }
{ return (top < 0); else
} {
Stack() int x = a[top--];
{ return x;
top = -1; }
} }
boolean push(int x) int peek()
{ {
if (top >= (MAX - 1)) if (top < 0)
{ {
System.out.println("Stack Overflow"); System.out.println("Stack Underflow");
return false; return 0;
} }
else else
{ {
a[++top] = x; int x = a[top];
System.out.println(x + " pushed into stack"); return x;
return true; }
} }
}
void print()
{
for(int i = top;i>-1;i--)
{
System.out.print(a[i]+ " ");
}
}
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
System.out.println("Top element is :" + s.peek());
System.out.print("Elements present in stack :");
s.print();
}
}
Applications of Stacks
Stacks can be used for:
• Expression evaluation
• To check parenthesis matching in an expression.
• Expression Conversion
Infix to Postfix
Infix to Prefix
Postfix to Infix
Prefix to Infix
• Memory Management.
Notations for Arithmetic
Expression
Infix Notation
The infix notation is a convenient way of writing an expression in which each operator is
placed between the operands. Infix expressions can be parenthesized or unparenthesized
depending upon the problem requirement.
A + B, (C - D)
Prefix Notation
The prefix notation places the operator before the operands.
+ A B, -CD
Postfix Notation
The postfix notation places the operator after the operands.
AB +, CD+
Precedence of operators
The precedence of operators determines which operator is executed first if
there is more than one operator in an expression.
Let us consider an example:
int x = 5 - 17* 6;
Associativity of Operators
The associativity of operators determines the direction in which an expression
is evaluated. For example,
b = a;
Find the result of following infix expression:
3+5*7 – 4 ^ 2
Ans: 22

500+5^3 – (10+56) * 9
Ans: 31

365*52*7+10/10

3+5*(7-4)^2

8*(5^4+2)-6^2/(9*3)
A+B / C*D – E/ (F+G)
Infix to Postfix A+B / C*D – E/ (F+G)

A+B / C*D – E/ (FG+)

A+BC\ *D – E/ (FG+)

A+BC\D* – E/ (FG+)

A+BC\D* – EFG+/

ABC\D*+ – EFG+/

ABC\D*+EFG+/-
(A+B)*(C-D)

Ans: AB+CD-*

D=A+B*C

Ans: DABC*+=

A+B / C+D * (E-F) ^ G

Ans: ABC\+DEF- G^*+


Infix to Postfix Conversion using Stack Data Structure

• Read all the symbols one by one from left to right in the given Infix Expression.
• If the reading symbol is operand, then directly print it to the result (Output).
• If the reading symbol is left parenthesis '(', then Push it on to the Stack.
• If the reading symbol is right parenthesis ')', then Pop all the contents of stack until
respective left parenthesis is poped and print each poped symbol to the result.
• If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack.
However, first pop the operators which are already on the stack that have higher or equal
precedence than current operator and print them to the result.
(A+B)*(C-D)
AB+CD-*
let us consider the following infix expression 2 * (4+3) - 5.

Its equivalent postfix expression is 2 4 3 + * 5-


Queue
A queue is a useful data structure in programming.
Queue follows the First In First Out (FIFO) rule - the item that goes in first
is the item that comes out first.

 In programming terms, putting items in the queue is called enqueue.

 Removing items from the queue is called dequeue.


Basic Operations of Queue
A queue is an object (an abstract data structure - ADT) that allows the
following operations:

Enqueue: Add an element to the end of the queue


Dequeue: Remove an element from the front of the queue
IsEmpty: Check if the queue is empty
IsFull: Check if the queue is full
Peek: Get the value of the front of the queue without removing it
Working of Queue
Queue operations work as follows:

Two pointers: FRONT and REAR


FRONT track the first element of the queue
REAR track the last element of the queue
Initially, set value of FRONT and REAR to -1
Enqueue
To enqueue the data,
Check if the queue is full.
If its full
we can't insert data.
Otherwise
insert the data in arr[rear] and increment the rear variable by 1.
Enqueue the Elements: 10,20,30,40,50

rear

front 10

Insert elements from rear end


public Queue(int size)
{
this.maxSize = size;
this.queueArray = new int[size];
front = 0;
rear = -1;
currentSize = 0;
}
public void enqueue(int item)
{
if(isQueueFull())
{
System.out.println("Queue is full!");
return;
}
if(rear == maxSize - 1)
{
rear = -1;
}
queueArray[++rear] = item;
currentSize++;
System.out.println("Item added to queue: " + item);
}
boolean isQueueFull() { //Checks if the queue is full
return rear == size;
}

//adds element at the end of the queue


void enqueue(int val)
{
if(isQueueFull()) {
Sop("Queue is Full\n");
} else {
arr[rear] = val;
rear++;
}
}
Dequeue
To dequeue element from the queue,
Check if the queue is empty
if it's empty
We can't dequeue an element from the empty queue.
Otherwise
Print/return arr[front] and increment the front by 1.
public int delete()
{
if(isQueueEmpty())
{
throw new RuntimeException("Queue is empty");
}
int temp = queueArray[front++];
if(front == maxSize)
{
front = 0;
}
currentSize--;
return temp;
}
public int peek()
{
return queueArray[front];
}
// Queue:isFull Operation
public boolean isQueueFull()
{
return (maxSize == currentSize);
}
// Queue:isEmpty Operation
public boolean isQueueEmpty()
{
return (currentSize == 0);
}
int isQueueEmpty()
{
if(front == rear)
return 1;
return -1;
}
1.public class Queue
2.{ if(rear == maxSize - 1)
3. {
4. private int maxSize; rear = -1;
5. private int[] queueArray; }
6. private int front; queueArray[++rear] = item;
7. private int rear;
currentSize++;
8. private int currentSize;
9. public Queue(int size) System.out.println("Item added to queue: " + item)
10. { ;
11. this.maxSize = size; }
12. this.queueArray = new int[size]; public int Dequeue()
13. front = 0; { if(isQueueEmpty())
14. rear = -1; {
15. currentSize = 0; throw new RuntimeException("Queue is empty"
16. }
); }
17. public void enQueue (int item)
18. { int temp = queueArray[front++];
19. if(front == maxSize)
20. if(isQueueFull()) {
21. { front = 0;
22. System.out.println("Queue is full!"); }
23. return; currentSize--;
24. } return temp;
}
public static void main(String[] args)
{
CircularQueue q = new CircularQueue(5);
q.enQueue(14);
q.enQueue(22);
q.enQueue(13);
q.enQueue(-6);
q.displayQueue();
int x = q.deQueue();
if(x != -1)
{
System.out.print("Deleted value = ");
System.out.println(x);
}
x = q.deQueue();
if(x != -1)
{
System.out.print("Deleted value = ");
System.out.println(x);
}
q.displayQueue();
q.enQueue(9);
q.enQueue(20);
q.enQueue(5);
q.displayQueue();
q.enQueue(20);
}
}
public void displayQueue() else
{ {
if(front == -1)
for(int i = front; i < size; i++)
{
System.out.print("Queue is Empty");
{
return; System.out.print(queue.get(i));
} System.out.print(" ");
System.out.print("Elements in the " + }
"circular queue are: "); for(int i = 0; i <= rear; i++)
if(rear >= front) {
{ System.out.print(queue.get(i));
for(int i = front; i <= rear; i++)
System.out.print(" ");
{
System.out.print(queue.get(i));
}
System.out.print(" "); System.out.println();
} }
System.out.println(); }
}
Time Complexity of Enqueue : O(1)
Time Complexity of Dequeue : O(n)
import java.util.Scanner;

class Queue {
private static final int maxsize = 5;
int[] queue = new int[maxsize];
int front = -1;
int rear = -1;
void main () {
Scanner scanner = new Scanner(System.in);
Queue q = new Queue();
int choice;
do {
Sop("\n1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\n");
Sop("\nEnter your choice ?");
choice = scanner.nextInt();
switch (choice) {
case 1: Sop("Enter the element to insert: ");
int data = scanner.nextInt();
q.insert(data);
break;
case 2:
q.delete();
break;
case 3:
q.display();
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Enter a valid choice!");
}
} while (choice != 4);

scanner.close();
}
}
void insert() {

Scanner scanner = new Scanner(System.in);


Sop("\nEnter the element:");
int item = scanner.nextInt();

if(rear == maxsize-1) {
Sop("\nOVERFLOW\n");
return;
}
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
} else {
rear = rear+1;
}
queue[rear] = item;
Sop("\nValue inserted ");

}
void delete() {

if (front == -1 || front > rear) {


Sop("\nUNDERFLOW\n");
void display() {
return;
if(rear == -1) {
}
Sop("\nEmpty queue\n");
else
} else {
{
Sop("\nprinting values .....\n");
int item = queue[front];
if(front == rear) {
for(int i=front; i<=rear; i++) {
front = -1;
Sop(queue[i]);
rear = -1 ;
}
}
}
else
}
{
front = front + 1;
}
Sop("\nvalue deleted ");
}
}
class Queue { if (front == rear) {
static private int front, rear, capacity;
static private int queue[]; System.out.printf("\nQueue is empty\n");
return;
Queue(int c) }
{ else {
front = rear = 0; for (int i = 0; i < rear - 1; i++) {
capacity = c; queue[i] = queue[i + 1];
queue = new int[capacity]; }
} if (rear < capacity)
static void queueEnqueue(int data) queue[rear] = 0;
{ rear--;
if (capacity == rear) { }
System.out.printf("\nQueue is full\n"); return;
return; }
} static void queueDisplay()
else { {
queue[rear] = data; int i;
rear++; if (front == rear) {
} System.out.printf("\nQueue is
return; Empty\n");
} return;
static void queueDequeue() }
{
for (i = front; i < rear; i++) {
System.out.printf(" %d <-- ", queue[i]);
} q.queueEnqueue(20);
return; q.queueEnqueue(30);
} q.queueEnqueue(40);
static void queueFront() q.queueEnqueue(50);
{
if (front == rear) { q.queueDisplay();
System.out.printf("\nQueue is Empty\n"); q.queueEnqueue(60);
return; q.queueDisplay();
} q.queueDequeue();
System.out.printf("\nFront Element is: %d", q.queueDequeue();
queue[front]); System.out.printf(
return; "\n\nafter two node
} deletion\n\n");
}
public class StaticQueueinjava { q.queueDisplay();
public static void main(String[] args) q.queueFront();
{ }
Queue q = new Queue(4); }
q.queueDisplay();
Circular Queue
In a normal Queue Data Structure, we can insert elements until queue
becomes full.
But once the queue becomes full, we can not insert the next element until all
the elements are deleted from the queue.
 In the above situation, even though we have empty positions in the queue we
can not make use of them to insert the new element.

 This is the major problem in a normal queue data structure.

 To overcome this problem we use a circular queue data structure.


A circular queue is a linear data structure in which the operations are
performed based on FIFO (First In First Out) principle and the last position is
connected back to the first position to make a circle.
Let’s say the MaxSize of your queue is 5, and the rear pointer has already
reached the end of a queue.
There is one empty space at the beginning of a queue, which means that the
front pointer is pointing to location 1.
Rear + 1 = 4 + 1 = 5 (Overflow Error)
Rear = (Rear + 1)% MaxSize = 0 (Reached loc. 0 / Beginning of queue)
Implementation of Circular
Queue
Step 1 - Include all the header files which are used in the program and define
a constant 'SIZE' with specific value.
Step 2 - Declare all user defined functions used in circular queue
implementation.
Step 3 - Create a one dimensional array with above defined SIZE (int
cQueue[SIZE])
Step 4 - Define two integer variables 'front' and 'rear' and initialize both with
'-1'. (int front = -1, rear = -1)
Step 5 - Implement main method by displaying menu of operations list and
make suitable function calls to perform operation selected by the user on
circular queue.
enQueue(value)
Step 1: Check if the queue is full (Rear + 1 % Maxsize = Front)
Step 2: If the queue is full, there will be an Overflow error
Step 3: Check if the queue is empty, and set both Front and Rear to 0
To insert elements:
Step 4: If Rear = Maxsize - 1 & Front != 0 (rear pointer is at the end of the
queue and front is not at 0th index), then set Rear = 0
Step 5: Otherwise, set Rear = (Rear + 1) % Maxsize
Step 6: Insert the element into the queue (Queue[Rear] = x)
Step 7: Exit
deQueue()
Step 1: Check if the queue is empty (Front = -1 & Rear = -1)
Step 2: If the queue is empty, Underflow error
Step 3: Set Element = Queue[Front]
Step 4: If there is only one element in a queue,
set both Front and Rear to -1 (IF Front = Rear, set Front = Rear = -1)
Step 5: And if Front = Maxsize -1 set Front = 0
Step 6: Otherwise, set Front = Front + 1
Step 7: Exit
display()
Step 1 - Check whether queue is EMPTY. (front == -1)
Step 2 - If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the
function.
Step 3 - If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front'.
Step 4 - Check whether 'front <= rear', if it is TRUE, then display 'queue[i]' value
and increment 'i' value by one (i++).
Repeat the same until 'i <= rear' becomes FALSE.
Step 5 - If 'front <= rear' is FALSE, then display 'queue[i]' value and increment 'i'
value by one (i++).
Repeat the same until'i <= SIZE - 1' becomes FALSE.
Step 6 - Set i to 0.
Step 7 - Again display 'cQueue[i]' value and increment i value by one (i++).
Repeat the same until 'i <= rear' becomes FALSE.
Priority queue
It is an abstract data type that provides a way to maintain the dataset.
The “normal” queue follows a pattern of first-in-first-out.
It dequeues elements in the same order followed at the time of insertion
operation.
A priority queue is a special type of queue in which each element is
associated with a priority value.
And, elements are served on the basis of their priority.
That is, higher priority elements are served first.
However, if elements with the same priority occur, they are served according
to their order in the queue.
Assigning Priority Value
Generally, the value of the element itself is considered for assigning the
priority. For example,
The element with the highest value is considered the highest priority
element.
However, in other cases, we can assume the element with the lowest value as
the highest priority element.
We can also set priorities according to our needs.
Characteristics of Priority Queue
Priority queue in a data structure is an extension of a linear queue that
possesses the following properties:
Every element has a certain priority assigned to it.
Every element of this queue must be comparable.
It will delete the element with higher priority before the element
with lower priority.
If multiple elements have the same priority, it does their removal from the
queue according to the FCFS principle.
Difference between Priority Queue and Normal Queue
In a queue, the first-in-first-out rule is implemented whereas, in a priority
queue, the values are removed on the basis of priority.
The element with the highest priority is removed first.
A priority queue is of two types:
Ascending Order Priority Queue
An ascending order priority queue gives the highest priority to the lower
number in that queue
Ex: 4, 8, 12, 45, 35, 20.
Firstly, you will arrange these numbers in ascending order as follows:
4, 8, 12, 20. 35, 45.
In this list, 4 is the smallest number. Hence, the ascending order priority
queue treats number 4 as the highest priority.
Descending Order Priority Queue
A descending order priority queue gives the highest priority to the highest
number in that queue.
Ex: 4, 8, 12, 45, 35, 20.
Firstly, you will arrange these numbers in ascending order as follows:
45, 35, 20, 12, 8, 4.
In this list, 45 is the highest number. Hence, the descending order priority
queue treats number 45 as the highest priority.
Implementation of the Priority
Queue in Data Structure
You can implement the priority queues in one of the following ways:
Linked list
Binary heap
Arrays
Binary search tree
The binary heap is the most efficient method for implementing the priority
queue in the data structure.
Consider you have to insert 7, 2, 45, 32, and 12 in a priority queue.
The element with the least value has the highest property. Thus, you should
maintain the lowest element at the front node.
Binary Heap
A binary heap tree organizes all the parent and child nodes of the tree in a
particular order. In a binary heap tree, a parent node can have a maximum
of 2 child nodes. The value of the parent node could either be:
equal to or less than the value of a child node.
equal to or more than the value of a child node.
The above process divides the binary heap into two types: max heap and
min-heap.
Max Heap
The max heap is a binary heap in which a parent node has a value either
equal to or greater than the child node value. The root node of the tree has
the highest value.
Inserting an Element in a Max Heap Binary Tree
The algorithm scans the tree from top to bottom and left to right to find an
empty slot.
It then inserts the element at the last node in the tree.
After inserting the element, the order of the binary tree is disturbed.
You must swap the data with each other to sort the order of the max heap
binary tree.
You must keep shuffling the data until the tree satisfies the max-heap
property.
Deletion in Priority Queue:
As you know that in a max heap, the maximum element is the root node.
And it will remove the element which has maximum priority first.
Thus, you remove the root node from the queue.
This removal creates an empty slot, which will be further filled with new
insertion.
Then, it compares the newly inserted element with all the elements inside the
queue to maintain the heap invariant.
Min Heap
The min-heap is a binary heap in which a parent node has a value equal to or
lesser than the child node value. The root node of the tree has the lowest
value.
Application of Queue in Data
Structure
•Managing requests on a single shared resource such as CPU scheduling and disk scheduling
•Handling of interrupts in real-time systems. The interrupts are handled in the same order as
they arrive i.e First come first served.
•Handling website traffic
•Routers and switches in networking
•Queues are used as buffers in most of the applications like MP3 media player, CD player, etc.
•Maintaining the playlist in media players
•In real life scenario, Call Center phone systems use Queues to hold people calling them in order,
until a service representative is free.

You might also like