Data Structures & Algorithms Syllabus
Data Structures & Algorithms Syllabus
MODULE 1
SYLLABUS
Basic Concepts of Data Structures Definitions; Data Abstraction; Performance Analysis - Time & Space
Complexity, Asymptotic Notations;
Polynomial representation using Arrays, Sparse matrix (Tuple representation); Stacks and Queues -
Stacks, Multi-Stacks, Queues, Circular Queues, Double Ended Queues; Evaluation of Expressions- Infix
to Postfix, Evaluating Postfix Expressions.
1. Requirement Phase:
• All programming projects begin with a set of specifications that defines the purpose of that program.
• Requirements describe the information that the programmers are given (input) and the results
(output) that must be produced.
• Frequently the initial specifications are defined vaguely and we must develop rigorous input and
output descriptions that include all cases.
2. Analysis Phase
• In this phase the problem is break down into manageable pieces.
• There are two approaches to analysis:-bottom up and top down.
• Bottom up approach is an older, unstructured strategy that places an early emphasis on coding fine
points. Since the programmer does not have a master plan for the project, the resulting program
frequently has many loosely connected, error ridden segments.
• Top down approach is a structured approach divide the program into manageable segments.
• This phase generates diagrams that are used to design the system.
• Several alternate solutions to the programming problem are developed and compared during this
phase
3. Design Phase
• This phase continues the work done in the analysis phase.
• The designer approaches the system from the perspectives of both data objects that the program
needs and the operations performed on them.
• The first perspective leads to the creation of abstract data types while the second requires the
specification of algorithms and a consideration of algorithm design strategies.
Ex: Designing a scheduling system for university
Data objects: Students, courses, professors etc
Operations: insert, remove search etc
ie. We might add a course to the list of university courses, search for the courses taught by
some professor etc.
• Since abstract data types and algorithm specifications are language independent.
• We must specify the information required for each data object and ignore coding details.
Ex: Student object should include name, phone number, social security number etc.
5. Verification Phase
• This phase consists of
➢ developing correctness proofs for the program
➢ Testing the program with a variety of input data.
➢ Removing errors.
Correctness of Proofs
• If done properly, the correctness of proofs and system test will indicate erroneous code.
• Removal of errors depends on the design and code.
• While debugging large undocumented program written in ‘spaghetti’ code, each corrected
error possibly generates several new errors.
• Debugging a well documented program that is divided into autonomous units that interact
through parameters is far easier. This especially true if each unit is tested separately and then
integrated into system.
ALGORITHMS
Definition: An algorithm is a finite set of instructions to accomplish a particular task. In addition, all
algorithms must satisfy the following criteria:
(1) Input. There are zero or more quantities that are externally supplied.
(2) Output. At least one quantity is produced.
(3) Definiteness. Each instruction is clear and unambiguous.
(4) Finiteness. If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates
after a finite number of steps.
(5) Effectiveness. Every instruction must be basic enough to be carried out, in principle, by a person using
only pencil and paper. It is not enough that each operation be definite as in (3); it also must be feasible.
We can describe algorithm in many ways
1. We can use a natural language like English
2. Graphical Representation called flow chart, but they work well only if the algorithm is small and
simple.
Example [Selection sort]: Suppose we must devise an algorithm that sorts a collection of n > 1 elements
of arbitrary type. A simple solution is given by the following
[Selection Sort: In each pass of the selection sort, the smallest element is selected from the unsorted list
and exchanged with the elements at the beginning of the unsorted list]
For the first position in the sorted list, the whole list is scanned sequentially. The first position where 14 is
stored presently, we search the whole list and find that 10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list, appears
in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a linear manner.
We find that 14 is the second lowest value in the list and it should appear at the second place. We swap
these values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −
• From those elements that are currently unsorted, find the smallest and place it next in the sorted list
• We assume that the elements are stored in an array ‘list’, such that the ith integer is stored in the ith
Position list[i], 0 <= i <n
• Algorithm 1.1 is our first attempt to deriving a solution
printf("%dn", a[i]);
return 0;
}
• Correctness Proof
Recursive Algorithm
➢
• Examples:
Tabular Method
Statement s/e Frequency Total steps
float sum(float list[ ], int n) 0 0 0
{ 0 0 0
float tempsum = 0; 1 1 1
int i; 0 0 0
for(i=0; i <n; i++) 1 n+1 n+1
tempsum += list[i]; 1 n n
return tempsum; 1 1 1
} 0 0 0
Total 2n+3
s/e =steps/execution
4. Recursive summing of a list of numbers
Tabular Method
Statement s/e Frequency Total steps
float rsum(float list[ ], int n) 0 0 0
{ 0 0 0
if (n) 1 n+1 n+1
return rsum(list, n-1)+list[n-1]; 1 n n
return list[0]; 1 1 1
} 0 0 0
Total 2n+2
• When we analyze an algorithm it depends on the input data, there are three cases :
a. Best case: The best case is the minimum number of steps that can be executed for the given
parameters.
b. Average case: The average case is the average number of steps executed on instances with the
given parameters.
c. Worst case: In the worst case, is the maximum number of steps that can be executed for the
given parameters
ASYMPTOTIC NOTATION
• Complexity of an algorithm is usually a function of n.
• Behavior of this function is usually expressed in terms of one or more standard functions.
• Expressing the complexity function with reference to other known functions is called asymptotic
complexity.
• Three basic notations are used to express the asymptotic complexity
1. Big – Oh notation O
• Formal method of expressing the upper bound of an algorithm’s running time.
• i.e. it is a measure of longest amount of time it could possibly take for an algorithm to
complete.
• It is used to represent the worst case complexity.
• f(n) = O(g(n)) if and only if there are two positive constants c and n0 such that
f(n) ≤ c g(n) for all n ≥ n0 .
• Then we say that “f(n) is big-O of g(n)”.
• Examples:
1. Derive the Big – Oh notation for f(n) = 2n + 3
Ans:
2n + 3 <= 2n+3n
2n+3 <= 5n for all n>=1
Here c = 5
g(n) = n
so, f(n) = O(n)
T(n) Complexity
5n3+200n2+15 O(n3)
3n2+2300 O(n2)
2log n3 O(log n)
4n+log n O(n)
264 O(1)
2n+n1000 O(2n)
Eg. 1: 3n+2
f(n)=3n+2 ≤ 4n for all n≥2
≤ 4*n
≤ O(n)
= O(n2)
• Examples:
Derive the Big – Omega notation for f(n) = 2n + 3
Ans:
2n + 3 >= 1n for all n>=1
Here c = 1
g(n) = n
so, f(n) = Ω (n)
• Any algorithm is analyzed based on the unit of computation it performs. For linear search, we
need to count the number of comparisons performed, but each comparison may or may not search
the desired item.
• In Binary search algorithm, the target key is examined in a sorted sequence and this algorithm
starts searching with the middle item of the sorted sequence.
a. If the middle item is the target value, then the search item is found and it returns True.
b. If the target item < middle item, then search for the target value in the first half of the list.
c. If the target item > middle item, then search for the target value in the second half of the
list.
• In binary search as the list is ordered, so we can eliminate half of the values in the list in each
iteration.
• Consider an example, suppose we want to search 10 in a sorted array of elements, then we first
determine 15 the middle element of the array. As the middle item contains 18, which is greater
than the target value 10, so can discard the second half of the list and repeat the process to first
half of the array. This process is repeated until the desired target item is located in the list. If the
item is found then it returns True, otherwise False.
• In Binary Search, each comparison eliminates about half of the items from the list. Consider a list
with n items, then about n/2 items will be eliminated after first comparison. After second
comparison, n/4 items of the list will be eliminated. If this process is repeated for several times,
then there will be just one item left in the list. The number of comparisons required to reach to
this point is n/2i = 1. If we solve for i, then it gives us i = log2 n. The maximum number is
comparison is logarithmic in nature, hence the time complexity of binary search is O(log n).
where a, b, c …., k fall in the category of real numbers and 'n' is non negative integer, which is called the
degree of polynomial. An essential characteristic of the polynomial is that each term in the polynomial
expression consists of two parts:
1. one is the coefficient
2. other is the exponent
Eg, 10x2 + 26x,
here 10 and 26 are coefficients and 2, 1 is its exponential value.
The sign of each coefficient and exponent is stored within the coefficient and the exponent itself Additional
terms having equal exponent is possible one. The storage allocation for each term in the polynomial must
be done in ascending and descending order of their exponent.
Eg: B[][]=5x5+3x4-2x3+9
5 5
3 4
-2 3
9 0
Result[][]=A[][]+B[][]
5 5
3 4
-2 3
3 2
2 1
5 0
Algorithm POLY_ADDITION
Input: Two polynomial POLY1 and POLY2 with size of the row ptr1 and ptr2.
Output: Sum of two polynomial RESULT with row size, rptr
Data Structure: Polynomial is implemented using array.
Steps:
i=0,j=0, rptr=0
ptr1=row size of(POLY1), ptr2= row size of(POLY2)
While(i<ptr1 AND j<ptr2)
if( POLY1[i][1]=POLY2[j]][1]) then
RESULT[rptr][0]=POLY1[i][0]+POLY2[j][0]
RESULT[rptr][1]=POLY1[i][1]
i=i+1,
j=j+1,
rptr=rptr+1
ElseIf( POLY1[i][1]>POLY2[j][1])
RESULT[rptr][0]=POLY1[i][0]
RESULT[rptr][1]=POLY1[i][1]
i=i+1,rptr=rptr+1
Else
RESULT[rptr][0]=POLY2[j][0]
RESULT[rptr][1]=POLY2[j][1]
j=j+1,rptr=rptr+1
EndIf
EndWhile
While(i<ptr1)
RESULT[rptr][0]=POLY1[i][0]
RESULT[rptr][1]=POLY1[i][1]
i=i+1,rptr=rptr+1
EndWhile
While(j<ptr2)
RESULT[rptr][0]=POLY2[j][0]
RESULT[rptr][1]=POLY2[j][1]
j=j+1,rptr=rptr+1
EndWhile
Stop
The "POLY_ADDITION" algorithm combines two sparse polynomials represented as matrices (POLY1 and
POLY2) and outputs the sum in another sparse matrix (RESULT). It uses three pointers to traverse the rows
of the input matrices, comparing the exponents of corresponding terms. When the exponents match, it adds
the coefficients and stores the result in the output matrix. The algorithm efficiently handles sparse
polynomials by avoiding unnecessary zero terms in the result and ensures a compact representation of the
sum.
SPARSE MATRIX
It is a special array that contains more number of zero values than the non-zero values for their elements
Eg:
No of zero elements =6
No. of non zero elements = 3
Therefore, it’s a sparse matrix
0 1 7
0 0 0
0 0 2
A sparse matrix =2D sparse array. A matrix is said to be a sparse matrix if most of its elements are zero.
A dense matrix is a matrix that is not sparse. The density of a matrix is the percentage of entries that are
non-zero. If most of the elements are zero then the occurrence of zero elements in a large array is both a
computational and storage inconvenience
Alternative Representations
1. Array representation
2. Dynamic representation
ARRAY Representation (Tuple matrix)
All non-zero elements are stored in another array of triplet
◦ No of rows in the new array = No. of non – zero elements + 1
◦ No. of columns in the new array = 3
Triplet contains
◦ row number of the non-zero element
◦ column number of the non-zero element
◦ Value of non-zero element
Triplet can be represented by
◦ <Row, Col, Element>
0 0 2 3 2 2
2. TUPLE[k][1]=j
3. TUPLE[k][2]=A[i][j]
2. EndIf
2. j=j+1
3. EndWhile
2. i=i+1
3. EndWhile
4. TUPLE[0][0]=r
5. TUPLE[0][1]=c
6. TUPLE[0][2]=count
7. End
0 1 4
0 0 7 0
Convert to 1 2 7
6 0 0 0 Sparse Matrix
2 0 6
0 0 0 3 3 4 3
0 3 3
1 0 0 0
1 0 1
2 0 0 0
2 0 2
3 4 3
0 1 4
1 2 7
2 0 6
3 4 3 3 4 5
0 3 3 0 1 4
1 0 1 0 3 3
2 0 2 1 0 1
1 2 7
2 0 8
3 4 3 3 4 3 3 4 4
0 1 4 1 0 3 0 1 4
1 2 7 1 2 1 1 0 3
2 0 6 2 0 2 1 2 8
2 0 8
If ((TUPLE1 [i][0] < TUPLE2 [j][0] ))
SUM [ptr][0] =TUPLE1 [i][0]
SUM [ptr][1] =TUPLE1 [ i][1]
SUM [ptr][2] =TUPLE1 [ i][2]
i=i+1,
ptr=ptr+1,
elem=elem+1
3 4 3
1 0 4
1 2 7
2 0 6
3 4 3 3 4 4
0 1 3 0 1 3
1 2 1 1 0 4
2 0 2 1 2 8
2 0 8
If ((TUPLE1 [i][0] > TUPLE2 [j][0] ))
SUM [ptr][0] =TUPLE2 [j][0]
SUM [ptr][1] =TUPLE2 [ j][1]
SUM [ptr][2] =TUPLE2 [ j][2]
j=j+1,
ptr=ptr+1,
elem=elem+1
3 4 3 3 4 3 3 4 4
0 1 4 0 1 3 0 1 7
1 2 7 1 0 1 1 0 1
2 0 6 2 0 2 1 2 7
2 0 8
3 4 3 3 4 3 3 4 4
0 1 4 0 1 3 0 1 7
1 0 7 1 2 1 1 0 7
2 0 6 2 0 2 1 2 7
2 0 8
3 4 3 3 4 3 3 4 4
0 1 4 0 1 3 0 1 7
1 0 7 1 2 1 1 0 7
2 0 6 2 0 2 1 2 7
2 0 8
3 4 3 3 4 3 3 4 4
0 1 4 0 1 3 0 1 7
1 2 7 1 0 1 1 0 1
2 0 6 2 0 2 1 2 7
2 0 8
3 4 3 3 4 3 3 4 6
1 0 4 0 0 3 0 0 3
1 1 7 0 1 1 0 1 1
1 2 6 0 2 2 0 2 2
1 0 4
1 1 7
1 2 6
While(i<n1)
SUM[ptr][0]=TUPLE1[i][0]
SUM[ptr][1]=TUPLE1[i][1]
SUM[ptr][2]=TUPLE1[i][2]
i=i+1,
ptr=ptr+1,
elem=elem+1
EndWhile
After completing an iteration there are elements left in tuple2 we have to copy it fully to sum matrix
3 4 3 3 4 3 3 4 6
0 0 4 1 0 3 0 0 4
0 1 7 1 1 1 0 1 7
0 2 6 1 2 2 0 2 6
1 0 3
1 1 1
1 2 2
While(i<n1)
SUM[ptr][0]=TUPLE1[i][0]
SUM[ptr][1]=TUPLE1[i][1]
SUM[ptr][2]=TUPLE1[i][2]
i=i+1,
ptr=ptr+1,
elem=elem+1
EndWhile
Stack
Stack is a Linear Data structure. It is an ordered collection of homogeneous data elements where insertion
and deletion takes place at one end only. Eg: shunting of trains in a railway yard, Plates on a tray, Stack of
books. It follows a Last In First Out order. It can be implemented in two ways
• Static implementation -using array. It is a very simple technique, but it is not flexible. The size of the
stack has to be declared during program design and after that size cannot be varied
• Dynamic implementation –using Linked List. It uses pointers to implement stack. It is more efficient
• TOP>=SIZE-1 – overflow, stack is full
• Top= -1 –underflow, stack is empty
Operations of Stack
1. PUSH
2. POP
Insertion and deletion is at TOP of the stack
An element in a stack : ITEM
The maximum no of elements a stack can accommodate : SIZE
PUSH
Insert an item to stack
Algorithm Push_Array
• Input: The new item ITEM to be pushed.
• Output: A stack with newly pushed ITEM at the TOP position
• DS: An array A with TOP as the pointer.
Steps:
1. If TOP>=SIZE-1 then
a. Print “Stack full”
2. Else
a. TOP=TOP+1
b. A[TOP]=ITEM
3. EndIF
4. Stop
POP
Delete an item to stack
Algorithm Pop_Array
Stack -Status
Algorithm Status_Array
• Input: A stack with elements.
• Output: State whether it is empty or full, available free space and item at TOP
• DS: An array A with TOP as the pointer.
Steps:
1. If TOP<0 then
a. Print “ Stack is empty”
2. Else
a. If TOP>=SIZE-1 then
i. Print “ Stack is full”
b. Else
i. Print “Element at the TOP is”, A[TOP]
ii. Free=(SIZE-1-TOP)/SIZE*100
iii. Print “Percentage of free stack is”,free
c. Endif
3. EndIf
4. Stop.
Applications of stack
1. String Reversal
2. Evaluation of Arithmetic expression
1. Infix to postfix conversion
2. Postfix evaluation
3. Activation Record Management
4. Multiple Stack
5. Tower Hanoi
Human beings are quite used to work with infix notation, but infix is much complex and required to
remember set of rules. (E.g. precedence and associativity). Computer have to scan left to right several times
to evaluate infix expression. Postfix is much easy to work, and no need for operator precedence and other
rules. Computer can evaluate an expression in a single scan
Infix to Postfix
Rules to be remembered during infix to postfix conversion:
1. Parenthesize the expression starting from left to right.
2. During parenthesize the expression, operands associated with operator having higher Precedence are
first parenthesized.
3. The sub expression which has been converted into postfix is to be treated as single operand.
4. Once the expression is converted to postfix form, remove the parenthesis.
Infix Postfix
A+B AB+
12 + 60 – 23 12 60 + 23 –
(A + B)*(C – D ) AB+CD–*
A B * C – D + E/F A B C*D – E F/+
You should formulate the conversion algorithm using the following six rules:
1. Scan the input string (infix notation) from left to right. One pass is sufficient.
2. If the next symbol scanned is an operand, it may be immediately appended to the postfix string.
3. If the next symbol is an operator,
i. Pop and append to the postfix string every operator on the stack that
a) is above the most recently scanned left parenthesis, and
b) has precedence higher than or is a right-associative operator of equal precedence to
that of the new operator symbol.
ii. Push the new operator onto the stack.
4. When a left parenthesis is seen, it must be pushed onto the stack.
5. When a right parenthesis is seen, all operators down to the most recently scanned left parenthesis
must be popped and appended to the postfix string. Furthermore, this pair of parentheses must be
discarded.
6. When the infix string is completely scanned, the stack may still contain some operators. [Why are
there no parentheses on the stack at this point?] All the remaining operators should be popped and
appended to the postfix string.
ALGORITHM
1. Scan all the symbols one by one from left to right in the given Infix Expression.
2. If the reading symbol is an operand, then immediately append it to the Postfix Expression.
3. If the reading symbol is left parenthesis ‘( ‘, then Push it onto the Stack.
4. If the reading symbol is right parenthesis ‘)’, then Pop all the contents of the stack until the respective
left parenthesis is popped and append each popped symbol to Postfix Expression.
5. If the reading symbol is an operator (+, –, *, /), then Push it onto the Stack. However, first, pop the
operators which are already on the stack that have higher or equal precedence than the current
operator and append them to the postfix. If an open parenthesis is there on top of the stack then push
the operator into the stack.
6. If the input is over, pop all the remaining symbols from the stack and append them to the postfix.
abc/-ad/e-*
TOP→ a
abc/-ad/e-*
b
TOP→ a
abc/-ad/e-* c
b
TOP→ a
a
TOP→ (a-(b/c))
d
a
TOP→ (a-(b/c))
abc/-ad/e-*
e
(a/d)
TOP→ (a-(b/c))
10. ‘-’ is an operator. Pop two operand from stack
abc/-ad/e-*
Operand1=e
Operand 2=(a/d)
Operator= -
Push back result after evaluating= ((a/d)-e)
((a/d)-e)
TOP→ (a-(b/c))
String Reversal
Push the string to the stack and then pop it back and print it to display in reverse order
Algorithm ReverseStringWithStack(inputString):
stack = empty stack // Initialize an empty stack data structure
// Step 2: Pop each character from the stack and append it to the reversedString
while stack is not empty:
// Step 2.1: Pop the top character from the stack
poppedCharacter = [Link]()
// Step 2.2: Append the popped character to the reversedString
reversedString += poppedCharacter
// Step 2.3: Repeat until the stack is empty
return reversedString
Queue
A queue is an ordered list, a linear structure, insertions take place at one end, the rear, and deletions take
place at the other end, the front.
Two operations on the queue are
• Insertion (ENQUEUE): Take place at the end called REAR
• Deletion (DEQUEUE): Take place at other end called FRONT
Restrictions on queue
• the first element which is inserted into the queue will be the first one to be removed.
• queues are known as First In First Out (FIFO) lists.
Representation of Queues
Two ways to represent a queue in memory
◦ Using an Array
◦ Using Linked List
FRON REAR
T1 2 3 4 5 6 7
Deletion Insertion
Insertion(ENQUEUE)
Initially the queue will be initialized as
front= -1 and rear = -1. Before inserting check whether the queue is full or not. If not full, then insert the
element to (REAR+1). Make sure that the front always points to the first element by incrementing the front
pointer when the first element is inserted.
Deletion(DEQUEUE)
Before deleting, check whether the queue is empty or not. If not empty, then delete the element. Make sure
that the FRONT and REAR always points to -1 by decrementing the pointers when the last element is deleted.
Check whether queue is empty.
Rear>=Front and Front!=-1 NOT EMPTY
FRONT=0 1
2
3
REAR=3 4
FRONT=1 2
3
REAR=3 4
FRONT=2 3
REAR=3 4
FRONT=3 REAR=3 4
FRONT=-1, REAR=-1
i. FRONT=FRONT+1
d. EndIf
3. EndIf
4. Stop
Limitation
Disadvantages of the above implementation is as we delete element from the queue, the queue moves down
array. So, the storage space in the beginning is discarded and never used again.
Solution
Keep FRONT always at the zero index position. To maintain front at zero index position, every delete
operation would require shifting of all succeeding element in the array by one position
Advantages:
• It enables us to utilize all the empty position in an array i.e. no wastage of space.
Disadvantages:
• Every delete operation requires shift all the succeeding elements in the queue by one position . If the
queue is lengthy, this can be very time consuming
Circular Queue
A circular queue is a data structure that follows the First-In-First-Out (FIFO) principle, but with a circular
arrangement of elements in a fixed-size array. It avoids wasting space by reusing freed space from dequeued
elements. Circular queues have front and rear pointers that wrap around the array, allowing continuous
insertion and deletion operations without the need to shift elements.
QUEUE IS FULL
25 30 51 60 80
FRONT REAR
Physically circular array same as ordinary array, say Q[0..N-1], but Q[0] comes in between Q[1] and Q[N-
1] . Both pointers will move in same direction.
Example: If the current pointer is at position i, then the next location will be (i+1) MOD SIZE.
◦ i.e, if size =8
◦ Current position = 1 then next position = 2
◦ Current position = 7 then next position = (7+1) MOD 8 =0
Insertion(C-ENQUEUE)
Initially the queue will be initialized as front= -1 and rear = -1. Before inserting check whether the queue is
full or not. If not full, then insert the element to (REAR+1) MOD SIZE. Make sure that the front always
points to the first element by incrementing the front pointer when the first element is inserted.
Algorithm C-ENQUEUE(ITEM)
Input: An element ITEM to be
inserted into the circular queue
Output: Circular queue with the ITEM , if not full
Data Structure: CQ is implemented by using array
Steps:
1. next=(REAR+1) mod SIZE
2. If next=FRONT
a. Print” Queue is full”
3. Else
a. REAR=next
b. Q[REAR]=ITEM
c. If FRONT=-1 then
i. FRONT=0
d. EndIf
4. EndIf
5. Stop
Deletion (C-DEQUEUE)
Algorithm DEQUEUE()
Input: A Queue with n elements
Output: The deleted element is ITEM if the Queue is not empty.
Data Structure: CQ is implemented using array.
Steps:
1. If FRONT=-1 then
a. Print “Queue is Empty”
2. Else
a. ITEM=Q[FRONT]
b. If FRONT=REAR
i. FRONT=-1
ii. REAR=-1
c. Else
i. FRONT=(FRONT+1) mod SIZE
d. EndIf
3. EndIf
4. Stop
Consider a circular queue of size=4. Let’ see how these operations works in a circular queue.
1. ENCQUEUE(1)
Initially stack is empty
F=-1, R=-1
ENCQUEUE(1)
1
F=0, R=0
2. ENCQUEUE(2)
ENCQUEUE(2)
1 2
F=0 R=1
3. ENCQUEUE(3)
ENCQUEUE(3)
1 2 3
F=0 R=2
4. ENCQUEUE(4)
ENQUEUE(4)
1 2 3 4
F=0 R=3
5. DECQUEUE
DECQUEUE
2 3 4
F=1 R=3
6. ENCQUEUE(5)
ENCQUEUE(5)= REAR=(REAR+1)%SIZE=(3+1)%4=0
5 2 3 4
R=0 F=1
7. DECQUEUE
DECQUEUE, FRONT=FRONT+1%SIZE= (1+1)%4=2
5 3 4
R=0 F=2
8. ENCQUEUE(6)
ENCQUEUE(6) REAR=(REAR+1)%SIZE=(0+1)%4=1
5 6 3 4
R=1 F=2
9. DECQUEUE
DECQUEUE FRONT=FRONT+1%SIZE= (2+1)%4=3
5 6 4
R=1 F=3
10. DECQUEUE
DECQUEUE FRONT=FRONT+1%SIZE= (3+1)%4=0
5 6
F=0 R=1
11. DECQUEUE
DECQUEUE FRONT=FRONT+1%SIZE= (0+1)%4=1
6
F=1, R=1
12. DECQUEUE
DECQUEUE FRONT=REAR SO SET FRONT=-1, REAR=-1
F=-1, R=-1
Insertion→ Insertion
1 2 3
Deletion →Deletion
Representation of deque
Deque operations
The following are the operations of a Deque:
1. addFront(item) or Push_DQ(ITEM) adds a new item to the front of the deque.
2. addRear(item) or Inject(ITEM) adds a new item to the rear of the deque.
3. removeFront() or Pop_DQ() removes the front item from the deque
4. removeRear() or Eject() removes the rear item from the deque.
b. Q[front]=item
4. Else
a. i=rear
b. While(i>=front)
i. Q[i+1]=Q[i]
ii. i=i-1
c. End while
d. Q[front]=item
e. Rear++
5. End if
The "Push_DQ" or "addFront" algorithm inserts an item at the front of a deque (double-ended queue)
implemented using an array. It first checks if the deque is full, and if so, it prints a message and exits. If the
deque is not full, it handles cases where the front pointer is at the beginning or greater than 0. In the latter
case, it shifts elements to make space for the new item. Finally, it inserts the item at the front and updates
the rear pointer accordingly.
Inject(ITEM) or addRear(item)
Algorithm:
Input: deque with two pointer front and rear
Output: One item is inserted at rear of dequeue
Data Structure: Deque is implemented by using Array
Steps:
1. if(front==0 and rear=n-1)
a. Print “ Queue is full..”
b. Exit
2. If(front=-1)
a. Rear=0
b. Front=0
c. Q[front]=item
3. Else if(rear<n-1)
a. Rear++
b. Q[rear]=item
4. Else
a. i=front
b. While(i<=rear)
i. Q[i-1]=Q[i]
ii. i=i+1\
c. End while
d. Q[rear]=item
e. Front=front-1
5. End if
The "Inject" or "addRear" algorithm inserts an item at the rear of a deque (double-ended queue) implemented
using an array. It first checks if the deque is full, printing a message and exiting if so. Then, it handles cases
where the deque is initially empty or if there is space at the rear for the new item. In the latter case, it directly
adds the item at the rear. If the deque is full, it shifts elements to the right to create space for the new item,
updates the rear pointer, and adjusts the front pointer accordingly.
Pop_DQ() or removeFront()
Algorithm:
Input: deque with two pointer front and rear
Output: One item is deleted at front of dequeue
Data Structure: Deque is implemented by using Array
Steps:
1. if(front==-1 and rear=-1)
a. Print “ Queue is empty..”
b. Exit
2. Item=Q[front]
3. If(front==rear)
a. Rear=-1
b. Front=-1
4. Else
a. Front++
5. End if
6. Return item
The "Pop_DQ" or "removeFront" algorithm deletes an item from the front of a deque (double-ended queue)
implemented using an array. It first checks if the deque is empty, printing a message and exiting if so. Then,
it retrieves the item at the front of the deque. If the deque has only one element, it updates both the front and
rear pointers to -1. Otherwise, it increments the front pointer to remove the item. The algorithm then returns
the deleted item.
Eject() or removeRear()
Algorithm:
Input: deque with two pointer front and rear
Output: One item is deleted at rear of dequeue
Data Structure: Deque is implemented by using Array
Steps:
1. if(front==-1 and rear=-1)
a. Print “ Queue is empty..”
b. Exit
2. Item=Q[rear]
3. if(front==rear)
a. Rear=-1
b. Front=-1
4. Else
a. Rear—
5. End if
6. Return item
The "Eject" or "removeRear" algorithm deletes an item from the rear of a deque (double-ended queue)
implemented using an array. It first checks if the deque is empty, printing a message and exiting if so. Then,
it retrieves the item at the rear of the deque. If the deque has only one element, it updates both the front and
rear pointers to -1. Otherwise, it decrements the rear pointer to remove the item. The algorithm then returns
the deleted item.
Types of deque
There are two types of deque -
1. Input restricted queue
2. Output restricted queue
In an input-restricted queue, elements can only be inserted at one end (typically the rear), while deletion
operations are allowed from both ends. This design is useful when maintaining a specific order of insertion
is essential, but elements need to be dequeued from either end based on specific requirements. It provides a
balance between sequential insertion and flexible dequeuing.
Insertion→
1 2 3
Deletion →Deletion
FRONT REAR