0% found this document useful (0 votes)
5 views23 pages

Ds-Unit-Ii 2018 - 2019

A stack is a linear data structure that follows the Last In First Out (LIFO) principle, allowing items to be added or removed only from the top. The document outlines the Abstract Data Type (ADT) for stacks, various implementations using arrays and linked lists, and common operations such as push, pop, and peek. Additionally, it discusses applications of stacks in expression conversion and evaluation, as well as the concept of queues as First In First Out (FIFO) structures.
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)
5 views23 pages

Ds-Unit-Ii 2018 - 2019

A stack is a linear data structure that follows the Last In First Out (LIFO) principle, allowing items to be added or removed only from the top. The document outlines the Abstract Data Type (ADT) for stacks, various implementations using arrays and linked lists, and common operations such as push, pop, and peek. Additionally, it discusses applications of stacks in expression conversion and evaluation, as well as the concept of queues as First In First Out (FIFO) structures.
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/ 23

UNIT-II

Q. What is stack? Write its ADT. Explain briefly various representation in Stack
(2018)

Definition:- A STACK is a liner structure in which items may be added or remove only
at one end. An item may be added or removed only from the TOP of the STACK. This
means that the last item to be added to a STACK is the first item to be removed.
Accordingly STACK are also called “Last in First Out” (LIFO) Lists.

E
D top
D Top
C top C
C
B B
A top B top
B
top A
A A A

Initiation into a Stack

Initially the stack is empty as the elements A , B, C, D,E are inserted into it. The Stack
grows continuously upward.

D TOP

C C TOP

B B

A A

After deletion two elements of Stack


If two elements are deleted from Stack then the elements E and D are removed from the
stack.
ADT of stack:
AbstractDataType stack
{
instances
liner list of elements; one end is called the bottom; the other is the top;
operations
empty() : Return true if the stack is empty, return false other wise;
size() : Return the number of elements in the stack;
top() : Return the top element of the stack
pop() : Remove the top element from the stack;
push(x) : Add element x at the top of the stack;
}

Data Structures notes- unit - II Page 1


Memory representation of stack using Arrays:

To implement a stack we need a variable, called top that hold the index of the top element
of the stack and an array to hold the elements of stack.
Memory Representation of Stack

Stack 11 55 44 66 MAXSTK = 8

0 1 2 3 4 5 6 7
Top
class Stack
{
final int MAXSTK = 8;
int Stk[MAXSTK];
top = -1;
}
Stack S = new Stack();

In this case S is a objet of type Stack and S.Stk[top] is the top most element, when S is
initialized S.top equals to -1. After each insertion S.top increased by 1. Therefore to
check whether a Stack is empty or not, one can simply compare S.top with -1. If S.top
= -1 the Stack is empty otherwise the Stack is not Empty. Similarly to check whether a
Stack is full or not , one can simply compare S.top with MAXSTK-1. If S.top =
MAXSTK-1 then the Stack is full otherwise the Stack is not full.

Memory representation of stack using Linked list: Single linked list structure is
sufficient to represent any stack. Here , the data filed is for the item, and link filed is as
usual to point to the next item. Top is a pointer variable which will point to the top of the
stack. To initialize a stack one can simply set its top to NULL.

public class SinglyLinkedListNode {


public int value;
public SinglyLinkedListNode link;

public SinglyLinkedListNode(int value) {


this.value = value;
next = null;
}
}
10 850TOP

350
20 1065

850
30 null
1065

Data Structures notes- unit - II Page 2


Q. Explain about Stack Operations

Operation on a Stack|: The following operations that are usually performed on a stack
create() : Create an empty stack
isEmpty() : Return true if stack is empty, otherwise return false
isFull() : Return true if stack is full, otherwise return false
peek() : Return the top element of the stack
push(x) : Add an element x to the top of the stack
pop() : Delete the top element from the stack
display() : display the stack elements

Stack Algorithm Using Arrays :


Creating(S) : To create “S” as an empty Stack
class Stack
{
final int MAXSTK = 8;
int Stk[MAXSTK];
top = -1;
}
Stack S = new Stack();

push(S,X) : To insert the element ‘X’ on top of the Stack “S”


void push(Stack S, int X)
{
if(isFull(S))
{
print “Stack over flow”
return;
}
S.top++;
S.Stk[S.top]=X;
}
pop(S) : To remove the TOP element of the Stack “S”
void pop(Stack S)
{
if(isEmpty(S))
{
print “Stack is Under flow”
exit(0);
}
S.top--;
}
isEmpty(S) : To check whether the stack is empty or not. If return true if Stack is empty.
boolean isEmpty(Stack S)
{
if(S.top = - 1)
return(true)
else
return(false)
}

Data Structures notes- unit - II Page 3


isFull(S) : To check whether the Stack is full or not. It returns true if Stack is full.
boolean isFull(Stack S)
{
if(S.top == MAXSTK-1)
return(true);
else
return(false);
}
peek(S): To return the top element of Stack
int peek(Stack S)
{
if(isEmpty(S))
print “Stack Under flow”
else
return(S.Stk[S.top])
}

Display(S) : print the elements on the Stack


void Display(Stack S)
{
int i;
for(i=S.top;i>=0;i--)
print(S.Stk[i])
}

Stack Algorithm Using Linked List :


Create(S):
class node
{
int data;
node link;
}
class Stack
{
top =NULL;
}
Stack S = new Stack();

void Create(Stack s)
{
S=NULL;
}
IsEmpty( ):
int IsEmpty(Stack s)
{
if(s=NUL)
return(1);
Else
return(0);
}

Data Structures notes- unit - II Page 4


Push(x):
void Push( Stack s, int x)
{
Stack temp;
Temp=new node()
If(temp=NUL)
{
print(“out of memory space”)
Exit(0);
}
Temp.data=x;
Temp.link=s;
s=temp;
}
Pop( ):
int Pop(Stack s)
{
stack temp;
int x;
temp=s;
if(temp=NUL)
{
print(“stack empty”);
exit(0);
}
x=s.data;
s=s.link;
free(temp);
return(x);
}

Q. Write different application of stack with example (2017)


A stack is a LIFO structure, it is an appropriate data structure for applications in
which information must be saved and later retrieved in reverse order. Some of the app the
applications of stack are as follows:

1. Conversion of infix to postfix expression


2. Evaluation postfix expression
3. Evaluation of prefix expression
4. Conversion of infix to prefix expression
5. Implement of recursion

Recursion: - Recursion is an important tool to describe a procedure having several


repetitions of the same. A procedure is termed as recursive if the procedure is defined by
itself.
Example: int Factorial(int n)
{
int fact
if (n == 0)
fact = 1

Data Structures notes- unit - II Page 5


else
fact = n * Factorial(n-1);
return(fact);
}
Q. What is polish notation and Reverse Polish notation? Explain different types of
Polish notations. (2018)
Q. Write an algorithm and explain how to convert an infix expression into post fix
expression using stack. (2017)
The way to write arithmetic expression is known as a notation. An
arithmetic expression can be written in three different but equivalent notations, i.e.,
without changing the essence or output of an expression. These notations are −
 Infix Notation
 Prefix (Polish) Notation
 Postfix (Reverse-Polish) Notation
These notations are named as how they use operator in expression. We shall learn the
same here in this chapter.

Infix Notation:- We write expression in infix notation, e.g. a - b + c, where operators are
used in-between operands. It is easy for us humans to read, write, and speak in infix
notation but the same does not go well with computing devices. An algorithm to process
infix notation could be difficult and costly in terms of time and space consumption.

Prefix Notation:- In this notation, operator is prefixed to operands, i.e. operator is written
ahead of operands. For example, +ab. This is equivalent to its infix notation a + b. Prefix
notation is also known as Polish Notation.

Postfix Notation:- This notation style is known as Reversed Polish Notation. In this
notation style, the operator is postfixed to the operands i.e., the operator is written after
the operands. For example, ab+. This is equivalent to its infix notation a + b.

Procedure to convert from infix expression to postfix expression is as follows:

1. Scan the infix expression from left to right.

2. a) If the scanned symbol is left parenthesis, push it onto the stack.


b) If the scanned symbol is an operand, then place directly in the
postfix expression (output).
c) If the symbol scanned is a right parenthesis, then go on popping all
the items from the stack and place them in the postfix expression till
we get the matching left parenthesis.
d) If the scanned symbol is an operator, then go on removing all the
operators from the stack and place them in the postfix expression, if
and only if the precedence of the operator which is on the top of the
stack is greater than (or greater than or equal) to the precedence of
the scanned operator and push the scanned operator onto the stack
otherwise, push the scanned operator onto the stack.

Conversion of infix expression to postfix expression: Let E be an arithmetic expression


written in infix notation. Besides operands and operators, E may also contain left and

Data Structures notes- unit - II Page 6


right parentheses. The algorithm uses a stack to temporarily hold operators and left
parentheses. The postfix expression will be constructed from left to right using the
operands from E and the operators which are moved from stack. We begin by pushing a
left parentheses onto stack and adding a right parentheses at the end of E. The algorithm
is completed when stack is empty.

InfixToPostfix(E)
Step-1 : Push( ‘(‘ ) [Push-left parenthese ‘(‘ on to stack ]
Step-2: Repeat Step-3 to Step-20 while stack is not empty
Step-3: set item = E.scan_ch() [scan the symbol from infix expression]
Step-4: if (item = operand)
Step-5 write(item) [write the symbol into the output expression]
Step-6: if (item = ‘(‘ )
Step-7 push(item) [push symbol ‘(‘ to the stack]
Step-8: if (item = operator)
Step-9 x = pop() when
Step-10: if precedence(x) > precedence(item)
Step-11: repeat Step-12 to step-13 while (precedence(x) > precedence(item))
Step-12: x=pop()
Step-13: Write(x)
Step-14: while( precedence(x)=precedence(item))
Step-15: Push(item)
Step-16: if (item = ‘)’ )
Step-17: x = pop()
Step-18: Repeat Step-19 and Step-20 while (x <> ‘(‘ )
Step-19: write(x)
Step-20: x = pop()
Step-21 : Exit

Conversion of infix expression to prefix expression:


Input: E is an arithmetic expression in infix notation
Output: An arithmetic expression in prefix notation
Data Structure : Stack
Since two stacks are used
Push(s1, x) means adding an item x to stack s1
Pop(s1) means removing the top most element from the stack s1

InfixToPrefix(E)
Step-1: Initially add a left parenthesis ‘(‘ at the beginning of the infix expression E.
Step-2: push(s1, ‘)’ )
Step-3: set item = E.ReverseOrderScan_ch()
[scan the symbol from e in right to left manner]
Step-4: Repeat steps-5 to step-21 while stack s1 is not empty
Step-5: if( item = operand )
Step-6: push(s2,item)
Step-7: if item = ‘)’
Step-8: push(s1,item)
Step-9: if (item = operator)
Step-10: set x = pop(s1) when
Step-11: if (precedence(x) > precedence(item) )

Data Structures notes- unit - II Page 7


Step-12: Repeat step-13 to step-14 while precedence(x) > precedence(item)
Step-13: push(s1,item)
Step-14: set x=pop(s1)
Step-15: push(s2,x)
Step-16: Else if (precedence(x)= precedence(item))
Step-17: push(s1,item)
Step-18:Repeat step-19 to step-20 while (x=’(‘)
Step-19:x=pop(s1)
Step-20: Push(s2,x)
Step-21: repeat step-22 and step-24 while stack s2 is not empty
Step-22: set x = pop(s2)
Step-23: write(x)
Step-24: Exit

Q. Explain Evaluation of a postfix expression


EvalPostfix(P)
Step-1: Append a right parenthesis ‘)’ at the end of the postfix expression.
Step-2: Set item = P.scan_ch() [ Scan the symbol from postfix expression]
Step-3: Repeat Step-4 to Step-12 while item <> ‘)’
Step-4: if item = operand then
Step-5:Push(item) [operand is pushed in to the stack]
Step-6: if item = operator then
set a = Pop() [ a is the second operand of the current operator]
set b = Pop() [ b is the first operand of the current operator]
set op = item
set result = b op a
Step-7: Push(result)
Step-8: set item = P.Scan_ch() [End of Step 3 loop]
Step-9: set result = Pop()
Step-10: write (result).
Step-11: Exit

Q. Explain Evaluation of prefix expression


EvalPrefix(p)
Step-1: Append a left parenthesis ‘(‘ at the beginning of the prefix expression
Step-2: set item=p.ReverseOrderScan_ch()
[scan the symbol from P in right to left manner]
Step-3: Repeat step-4 to step-12 while item = ‘(‘
Step-4: if item = operand
Step-5: push(item) [operand push into the stack]
Step-6: if item = operator
Set a = pop() [ a is the first operand of the current operator]
Set b = pop() [b is the second operand of the current operator]
Set op = item
Set result = a op b
Step-7: push(result)
Step-8: set item = P.ReverseOrderScan_ch()
Step-9: set result = pop()
Step-10: write (result)
Step-11: Exit

Data Structures notes- unit - II Page 8


QUEUE

A Queue is a liner list of elements, deletions can takes place only at one end called the
FRONT and insertions can takes place only at the other end called the REAR. Queues are
also called First In First Out (FIFO) lists. Since the first element in a queue will be the
first element out of the queue. In other words the order in which elements entered into a
queue is the order in which they leave.

Memory Representation of Queue

A Queue may be represented in memory in Queue in two ways:


1. Array Representation
2. Linked List Representation

Array Representation of Queue:- To implement a Queue we need an one-dimensional


Array which holds that data item and other two variable FRONT which point to the
beginning of the Queue and a REAR which points to the end of the Queue. Suppose that
the elements of a Queue are of integer type elements and Queue can store maximum of
10 elements. The following are the necessary declarations.

class Queue
{
final int MAXQ = 10;
int front;
int rear;
int items[MAXQ];
}
Queue Q = new Queue();

In this case “Q” is a variable of type Queue during the initialization of Queue FRONT is
set to 0(zero) and REAR is set to -1 (minus one) an each addition of a Queue is the
variable REAR is incremented by 1 , on other hand in each deletion operation the
variable FRONT is incremented by 1.

FRONT = -1 0 1 2 3 4 5 6 7 8 9 MAXQ = 10
REAR = -1
Q=

Empty Queue

0 1 2 3 4 5 6 7 8 9

Q= A B C

FRONT REAR
A, B and then C inserted

Data Structures notes- unit - II Page 9


0 1 2 3 4 5 6 7 8 9

Q= B C

FRONT REAR (A is deleted)


0 1 2 3 4 5 6 7 8 9 FRONT = 1
REAR = 5
B C D E F
Q=

D,E and F inserted

Linked List Representation : One major drawback of representing a queue by using


array is that a fixed amount of storage remains allocated even when the structure is
actually using a small amount or possibly no storage at all. Further, no more than that
fixed amount of storage may be allocated , thus, introducing the possibility of overflow.

Class link
{
int data=d;
link next=null;
link front=null;
link rear=null;
}
link que= new link();

Linked representation of Queue

FORNT REAR
null 3025 35 1026 15 4365 45 235 80 null

625 3025 1026 4365 235

Here, Each node is divided into two fields

 Data which hold the data element


 Link which hold the address of the successor node

Apart from that we need two more variable

 FRONT which hold the address of the first node


 REAR which hold the address of the last node

Under the list representation of Q a special attention is required when the last element
is removed from a queue. In that case, REAR must also set to NULL, since in an empty
queue both FRONT and REAR must be NULL.

Data Structures notes- unit - II Page 10


ADT of Queue:

AbstractDataType queue
{
Instances:
ordered list of elements; one end is called the front; the other is the rear;

create(): To create a empty queue


IsEmpty() : Retrun true if the queue is empty, return false otherwise;
size() : Return the number of elements in the queue
front() : Return the front element of the queue;
back() : Return the back element of the queue;
pop() : Remove an element from the front of the queue
push(x) : Add element x at the back of the queue
IsFull():Retrun true if the queue is full, return false otherwise;
}

Operation on a Queue: ( Array Representation)


The following operations that are usually performed on a queue.

Create() : Create an empty Queue


isEmpty() : Return true if queue is empty, otherwise false
ifFull() : Return true if queue is full otherwise return false
insert(x) : Add element x to the queue
delete() : Delete the front element from the queue

Create(): Create as an empty Queue

void create( Queue Q)


{
Q.front = -1;
Q.rear=-1;
}

isEmpty(Queue Q): Return True if Q is empty otherwise return false

isEmpty(Queue Q)
{
if( front == -1)
print “Queue is empty”
else
print “Queue is not empty”
}

Data Structures notes- unit - II Page 11


isFull(Queue Q) : Return True if Q is full otherwise return false
isFull(Queue Q)
{
if(Q.rear = MAXQ-1)
print “Queue is full”
else
print “Queue is not full”
}

insert(Queue Q , int X): Add an element X to the rear of a Queue

void insert(Queue Q, int item)


{
if(isFull(Q))
{
Print ( “Queue is full”)
exit(0);
}
Else
If(Rear= -1) and if(front= -1)
Front=0;
else
{
Q.rear = Q.rear + 1;
Q.item[Q.rear] = item;
}

delete(Queue Q) : Remove front element from the Queue

void delete(Queue Q)
{
if(isEmpty(Q))
{
Print “Queue is Empty”
exit(0);
}
Else
Item = Q[front];
Q.front = Q.front+1;
}

display(Queue Q): Print all elements in Queue

void display(Queue Q)
{
for(i=Q.front;Q.front<Q.rear;i++)
print Q.item[i];
}

Data Structures notes- unit - II Page 12


Q. What is a Queue? Write an Algorithm to implement queue using linked list
(2018)

We can represent a queue as a linked list. In a queue data is deleted from the front end
and inserted at the rear end. We can perform similar operations on the two ends of a
list. We use two pointers front and rear for our linked queue implementation.

The linked queue looks as shown in figure 4.4:


front rear
100 400

10200 20300 30400 40X


100 200 300 400

Figure 4.4. Linked Queue representation

Operation on a Queue: ( Linked List Representation)

Create( ):

Class link
{
Int data = d;
Link next = null;
Link front = null;
Link frear = null;
}
Link que = new link( );

IsEmpty( ):

/* Return true if queue is empty */


IsEmpty( queue q)
{
If (q front = null)
Return (true);
Else
Return (false);
}

Insert( item ):

Void insert(queue q, int x)


{
If ( temp = null )
{
Print “out of memory space” ;
Exit (0);
}
Temp data = x;
Data Structures notes- unit - II Page 13
Temp link = null;
If (q rear == null )
q front = temp;
else
(qfront) link = temp;
q rear = temp;
rear = temp;
}

Delete( ):

Int Delete(queue q)
{
Int x;
If ( IsEmpty(q) )
{
Print “ queue is empty”
Exit(0);
}
Temp = q front;
X = temp data;
q front = temp next;
if (q front == null)
qrear = nu;;;
free(temp);
return(x);
}

Display( ):

void displayQ()
{
temp = front;
printf("\n\n\n\t\t Elements in the Queue are: ");
while(temp != NULL )
{
printf("%5d ", temp -> data);
temp = temp -> next;
}
}

Data Structures notes- unit - II Page 14


Circular Queue:- If the queue is represented using array when the rear pointer reaches at
the end, insertion will be denied even if room is available at the front. One way to remove
this is using circular array.

Circular Queue with 8 elements

Here we need two variables front and rear to keep track of the elements to be deleted and
inserted and therefore it maintains the unique characteristics of the queue
 Front will always be pointing to the first element front = -1 will indicate that the
queue is empty.
 Each time a new element is inserted into the queue the rear is incremented by 1 i.
rear = rear + 1.
 Each time a element is deleted from the queue the value of front is incremented
by 1 . i.e front = front + 1
 If front = rear then queue contains only one element (except front = rear = -1 )

Data Structures notes- unit - II Page 15


Operations on Circular Queue:

Create(Cqueue q)
{
q.front = -1;
q.rear = -1;
}

int IsEmpty(Cqueue q)
{
if(q.front == -1)
return( true)
else
return(false)
}

int isFull(Cqueue q)
{
if(q.front == (q.rear+1) % MAXQ)
return(true)
else
return(false)
}

Insertion: When an item is inserted into the circular queue we have to write
rear = rear + 1 % MAXQ
void insert(Cqueue q, int x)
{
if(isFull(q))
{
print “queue is full”
return
}
if(q.front == -1)
{
q.front = 0
q.rear=0
}
else
q.rear = (q.rear + 1) % ,MAXQ
q.items[q.rear]=x
}

Deletion: Whenever an element is deleted from the queue, the value of front is increased
by 1 i.e front = (front+1) % MAXQ. If front == -1, then queue is empty.

int Delete(Cqueue q)
{
int x;
if(isEmpty(q))

Data Structures notes- unit - II Page 16


{
print “queue empty”
exit(0);
}
x = q.item[q.front];
if(q.front == q.rear)
{
q.front = 0
q.rear = 0
}
else
q.front = (q.front+1) % MAXQ
return(x)
}

Q. What is Deque? What are the different techniques used to represent Deque?
Explain (2017)
A deque is a linear list in which elements can be added or removed at either end but not
in the middle. The term deque is a contraction of the name double-ended queue.

Front Rear

Deletion
Insertion 15 25 35 ……. 75 95 85

These are two variations of a deque. These two variations are due to the restrictions put to
perform either the insertions or deletions only at one end. They are

i. Input-restricted deque
ii. Output restricted deque

Input restricted and output restricted deques are intermediate between a deque and a
queue.
Input-restricted deque:
Front Rear

-- insertion
deletion deletion

Specifically, an input restricted deque is a deque which allows insertions at only one
end of the list but allows deletions at both end of the list.

Output-restricted deque:
Front Rear
Insertion insertion
deletion - --

An output-restricted deque is a deque which allows deletion at only one end of the list
but allows insertion at both end of the list.

Data Structures notes- unit - II Page 17


Since both insertion and deletion are performed from either end, it is necessary
to design algorithm to perform the following operations.

Operations of Deque:

i. insertFirst(e): insert e at the beginning of the deque


ii. insertLast(e): insert e at the end of the deque
iii. removeFirst(): remove and return the first element
iv. removeLast(): remove and return the last element
v. first(): return the first element
vi. last(): return the last element
vii. isEmpty(): return true if deque is empty; false otherwise
viii. size(): return the number of objects in the deque
Memory Representation of Deque:

a deque is implemented using either a circular array or a circular doubly linked list. In
a deque, two pointers are maintained, LEFT and RIGHT, which point to either end of
the deque. The elements in a deque extend from the LEFT end to the RIGHT end and
since it is circular, in a deque of N elements, Nth element of deque is followed by the first
element of the deque.

Data Structures notes- unit - II Page 18


Q. What are priority queue? Explain how it representation using arrays. (2018)
Priority Queues: A priority queue is a collection of elements such that each element has
been assigned a priority and such that the order in which elements are deleted and
processed comes from the following rules:

i. An element of higher priority is processed before an element of lower priority


ii. Two elements with the same priority are processed according to the order in
which they were added to the queue.

An example of priority queue in computer science occurs in timesharing system in which


the processes of higher priority is executed before any process of lower priority.
There are two types of priority queues:
1. Ascending priority queue
2. Descending priority queue
An ascending priority queue is a collection of items in to which items can be inserted
arbitrarily and from which only the smallest item can be removed. A descending priority
queue is similar but allows deletion of only the largest item.

 A priority queue can be represented in many ways. Here, we are discussing multi-
queue implementation of priority queue.

 Clearly, in this representation, shifting is required to make space for an element to


be inserted.
 To avoid this shifting, an alternative representation can be used (see Figure 4.7).
 In this representation, instead of representing queue corresponding to each
priority using a single array, a separate array for each priority is maintained.
 Each queue is implemented as a circular array and has its own two variables,
Front and Rear.
 The element with given priority number is inserted in the corresponding queue.
Similarly, whenever an element is to be deleted from the queue, it must be the
element from the highest priority queue.
 Note that lower priority number indicates higher priority.

Data Structures notes- unit - II Page 19


 If the size of each queue is same, then instead of multiple one-dimensional arrays,
a single two-dimensional array can be used where row i corresponds to the queue
of priority i.
 In addition, two single dimensional arrays are used. One is used to keep track of
front position and another to keep track of rear position of each queue (see Figure
4.8).

Q. What are the applications and limitations of queues? (2017)

Applications of Queue: As Queue is a FIFO structure, it is an appropriate data structure


for used in numerous applications of computer science. One important application of
queue is in simulation. Queues are mainly used to implement various aspects of operating
system. Some of the applications of queue are as follows:

 Simulation of traffic control system


 CPU scheduling in multiprogramming and time sharing environment
 Multilevel queue scheduling
 Multilevel feedback queue scheduling
 Round Robin scheduling algorithm.

Simulation:- Computer simulation imitates an activity in the real world using a computer
program in order to understand how the real-world process behaves. The advantage of
computer simulation is that you can easily change the program and observe impact of
modifications on the result. Simulation is the use of one system to initiate the behavior of
another system. The main goal of simulation is to help the user or to guess for obtaining
the output of the program after implementing some approaches.

Example: AQ

D
A

DQ BQ

C B

CQ
A Junction of four roads

Data Structures notes- unit - II Page 20


Consider the case of an automated traffic control system. Suppose in a junction four
roads meet as shown in above figure. There are four signals named A,B,C and D for the
traffics on the four roads. At a time only one signal can be turned on to allow the traffics
to pass. For example, the traffic from the queue AQ will be allowed to pass through other
three roads if the signal A is on. At that time the traffic in the queues BQ, CQ and DQ
will wait till their signals on. The simulation programs can be written to obtain the arrival
rate of traffics by using Poisson distribution.

CPU scheduling in multiprogramming and time sharing environment :- The


objective of multiprogramming is to have some process running at all times. In order to
maximize CPU utilization. In multiprogramming several processes are kept in memory at
one time. When one process is waiting for I/O , the operating system takes the CPU away
from that process and gives the CPU to another process. By switching the CPU among
processes, the operating system can make the computer more productive.

Multilevel Queue scheduling:- In multilevel queue scheduling the jobs to be executed


by the CPU are categorized into four different groups.

1. System process: In system process, the interrupts are to be serviced. Different


devices and terminals are connected with the CPU and they may interrupt at any
moment to get a service from it.
2. Interactive process(foreground process): Interactive users i.e foreground jobs
needs to be serviced.
3. Batch process (background process): Batch process i.e. background jobs needs to
be serviced.
4. Student process: Student process needs to be serviced.

In order to implement this complex scheduling is to classify the workload according to its
characteristics and to maintain separate process queues. In this we have maintained four
different queues. Each queue has its own scheduling algorithm. Process will be assigned
to their respective queues. CPU will then service the processes as per the priority of the
queues.

Event –Driven
Highest Priority System Process Scheduling

Shortest job
Foreground or
Interactive processes First scheduling
CPU
Round Robin
Background or Batch
processes scheduling

Lowest Priority Student Processes


FCFS Scheduling
Scheduling within queue

Data Structures notes- unit - II Page 21


The systems process queue having the highest priority of all and student process queue
having the lowest priority of all. Each queue has absolute priority over lower priority
queues. The processes from the highest priority queue (System process) are serviced until
the queue become empty. Then CPU switches to the queue of interactive process which is
having next lower priority and so on. A lower priority process is preempted by a higher-
priority arrival in one of the upper level queues. In the example no process in the student
queue could run unless the queue for system process, foreground process, background
process was all empty. If any foreground process entered the queue while a background
process was running the batch process would be preempted.

Multilevel feedback queue scheduling:

The drawback of multilevel queue strategy is as follows:

1. When process arrived in higher priority queues is very high, the processes in
lower priority queue may starve for a long time.
2. In multilevel queue scheduling , processes are permanently assigned to a queue
upon entry to the system and process do not move among queues.

The multilevel feedback queue scheduling overcomes both the difficulties. The first
problem could be solved by giving time slices between the queues. Each queue gets a
certain portion of the CPU time. Multilevel feedback queue strategy allows a process to
move between queues. If process uses too much CPU time, it will be moved to next lower
priority queue. A process that waits too long in a lower priority queue may be moved to
a higher priority queue.

Queue-1 8 milliseconds

16 milliseconds
Queue-2

Queue-3 FCFS

A process entering the system is put in queue-1. A process in queue-1 is given a time
quantum of 8 milliseconds. If it does not finish within this time, it is moved to the tail of
queue-2. If queue-1 is empty, the process at the front of queue-2 is given a time quantum
of 16 milliseconds. If it does not complete within this time quantum, it is preempted and
put into queue-3. Processes in queue-3 are served on a first-come-first-serve(FCFS) basis,
only when queue-1 and queue-2 are empty.

Round Robin scheduling algorithm:- The round-robin scheduling algorithm is


designed especially for time sharing systems. A small unit of time , called a time
quantum is defined. A time quantum is generally from 10 to 100 milliseconds.

Data Structures notes- unit - II Page 22


For an example, the set of processes with CPU burst time is given. The time quantum is 5
milliseconds.

Process CPU Burst Time(in milliseconds)

P1 20
P2 7
P3 9

The total CPU time required is 36 milliseconds.

P2 finished P3 finished P1 finished

P1 P2 P3 P1 P2 P3 P1 P1

0 5 10 15 20 22 26 31 36

The advantages of this kind of scheduling is reducing the average turn around time.

Turn around time for P1 = 36


Turn around time for P2 = 22
Turn around time for P3 = 26

Average turn around time = (36 + 22 + 26) / 3 = 28 milliseconds.

Q. What are the advantages and disadvantages of Queues?

Advantages of Queues:
 Circular Queues: Queues can lead to empty spaces in the data structure, since a
bigger array is needed than the total number of pieces of data. However, programmers
can use circular queues to use the empty space.
 Speed: Data queues are a fast method of inter-process communication. Data queues
free up jobs from performing some work, which can lead to a better response time
and an overall improvement in system performance.
 Multiple Jobs: some jobs have performance restraints and cannot handle all the
entries, so the data entries are spread out across multiple jobs. For example, only one
customer service representative can help a customer at a time, so the queue can
spread customer service requests among the representatives, for quicker processing.

Limitations of Queues:

 You cannot use Queue for LIFO operations nor you can store hierarchical data
in it.
 Queues are implemented in two ways: Using Arrays and and using Linked-List.
 Each has their own pros and cons.
 Array implementation has space limitations and hence limited capacity.
 Linked-list implementation solves this problem, but is slow.

Data Structures notes- unit - II Page 23

You might also like