Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE

JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Unit 1:
Short Answers: (2 Marks Each)
Q. 1. What is Data Structure? How you will classify it?

Data Structure can be classified in two categories. According to these categories we can access or manage data
according to our need. There are various ways to classify data structure.

• Primitive and Non Primitive Data Structure: The data structure that are atomic (indivisible) are called
primitive. Examples are integer, real and characters. The Data structures that are not atomic are called non-primitive
or composite. Examples are records, array and string.
• Linear and Non-Linear Data Structures: In a linear data structure, the data items are arranged in a linear
sequence. For Example: array. In a non-linear data structure, the data items that are not in sequence. For Example:
trees and graphs.
• Homogeneous and Non-Homogeneous Data Structures: In homogeneous data structure, all the elements are
of same type. For Example: arrays. In non-homogeneous data structure, the elements may or may not be of the same
type. For Example: Records.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

• Static and Dynamic Data Structures: Static data structures are those whose size and structures, associated
location is fixed at compile time.Dynamic structures are ones whose ones which expand or shrink as required during
the program execution and there associate memory location change.

Q. 2. What do you understand with asymptotic notation? Explain in detail.

Asymptotic Notations are the expressions that are used to represent the complexity of an algorithm. There are
three types of analysis that we perform on a particular algorithm.

Best Case: In which we analyse the performance of an algorithm for the input, for which the algorithm takes less
time or space.

Worst Case: In which we analyse the performance of an algorithm for the input, for which the algorithm takes long
time or space.

Average Case: In which we analyse the performance of an algorithm for the input, for which the algorithm takes
time or space that lies between best and worst case.

Types of Data Structure Asymptotic Notation

1. Big-O Notation (Ο) – Big O notation specifically describes worst case scenario.
2. Omega Notation (Ω) – Omega(Ω) notation specifically describes best case scenario.
3. Theta Notation (θ) – This notation represents the average complexity of an algorithm.

Big-O Notation (Ο)

Big O notation specifically describes worst case scenario. It represents the upper bound running time complexity of
an algorithm.

Omega Notation (Ω)

Omega notation specifically describes best case scenario. It represents the lower bound running time complexity of
an algorithm. So if we represent a complexity of an algorithm in Omega notation, it means that the algorithm cannot
be completed in less time than this.

Theta Notation (θ)


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

This notation describes both upper bound and lower bound of an algorithm so we can say that it defines exact
asymptotic behaviour. In the real case scenario the algorithm not always run on best and worst cases, the average
running time lies between best and worst and can be represented by the theta notation.

Q. 3 .What is Algorithm? Explain its Characteristics in detail.

Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the
desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be
implemented in more than one programming language.
Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have the following characteristics −
• Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their
inputs/outputs should be clear and must lead to only one meaning.
• Input − An algorithm should have 0 or more well-defined inputs.
• Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output.
• Finiteness − Algorithms must terminate after a finite number of steps.
• Feasibility − Should be feasible with the available resources.
• Independent − An algorithm should have step-by-step directions, which should be independent of any
programming code.

Q. 4 .Give Algorithm for Reversing list and Factorial Calculation.

Iterative Method

1. Initialize three pointers prev as NULL, curr as head and next as NULL.
2. Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next
// Now change next of current
// This is where actual reversing happens
curr->next = prev
// Move prev and curr one step forward
prev = curr
curr = next

Algorithm for calculate factorial value of a number:

[algorithm to calculate the factorial of a number]


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

step 1. Start
step 2. Read the number n
step 3. [Initialize]
i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact=fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop
[process finish of calculate the factorial value of a number]

Q. 5 .Explain muti-stack implementation using single array.

To implement multiple stacks in a single array, one approach is to divide the array in k slots of size n/k each, and fix
the slots for different stacks, we can use arr[0] to arr[n/k-1] for first stack, and arr[n/k] to arr[2n/k-1] for stack2 and so
on where arr[] is the array of size n.

Although this method is easy to understand, but the problem with this method is inefficient use of array space.A stack
push operation may result in stack overflow even if there is space available in arr[].

Algorithm:

1. Here we use 2 arrays min[] and max[] to represent the lower


and upper bounds for a stack

2. Array s[] stores the elements of the stack

3. Array top[] is used to store the top index for each stack

4. Variable ns represents the stack number

5. Variable size represents the size for each stack in an array

6. First we build a function init() to initialize the starting values

7. Then we have a function createstack() to create the stack


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

8. Function Push() & Pop() are used to push and pop an element to and from the stack

9. Function Display() is used to display the elements in a particular stack

Q.6. .Write difference between Array and Stack and Queue?

Difference between Stack and Queue Data Structures


STACKS QUEUES

Stacks are based on the LIFO principle,

i.e., the element inserted at the last, is the Queues are based on the FIFO principle, i.e., the element

first element to come out of the list. inserted at the first, is the first element to come out of the list.

Insertion and deletion in queues takes place from the opposite

Insertion and deletion in stacks takes place ends of the list. The insertion takes place at the rear of the list

only from one end of the list called the top. and the deletion takes place from the front of the list.

Insert operation is called push operation. Insert operation is called enqueue operation.

Delete operation is called pop operation. Delete operation is called dequeue operation.

In stacks we maintain only one pointer to In queues we maintain two pointers to access the list. The front

access the list, called the top, which pointer always points to the first element inserted in the list and

always points to the last element present in is still present, and the rear pointer always points to the last

the list. inserted element.

In stack we can access elements according to lifo but in array we can access elements on randomly from any
position.
Descriptive Answers: (5 to 20 Marks)
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q. 1 Define Stack and its applications. Explain its basic structure and its operations and implement a stack
using Dynamic array.

Stack is a linear data structure which follows a particular order in which the operations are performed. The order
may be LIFO(Last In First Out) or FILO(First In Last Out).
here are many real-life examples of a stack. Consider an example of plates stacked over one another in the canteen.
The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost
position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO(Last In First
Out)/FILO(First In Last Out) order.

Following are the applications of stack:

1. Expression Evaluation
2. Expression Conversion
i. Infix to Postfix
ii. Infix to Prefix
iii. Postfix to Infix
iv. Prefix to Infix
3. Backtracking
4. Memory Management

Growable array based stack

Stack primarily has two main operation namely push and pop, where push inserts an element at top and pop removes
an element from top of the stack.
Now, whenever an implementation of stack is considered its size is pre-determined or fixed. Even though it is
dynamically allocated, still once it is made its size cannot be changed. And hence a condition called “stack full”
arises.
But what if a stack can grow as more elements are inserted or more elements are going to be inserted in future.
Remember, we are talking about array based Stack. Growable Stack is the concept of allocating more memory such
that “stack full” condition does not arises easily.
A Growable array-based Stack can be implemented by allocating new memory larger than previous stack memory
and copying elements from old stack to new stack. And then at last change the name of new stack to the name which
was given to old stack
There are two strategy for growable stack:
1. Tight Strategy : Add a constant amount to the old stack (N+c)
2. Growth Strategy : Double the size of old stack (2N)
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

There are two operation on growable stack:

1. Regular Push Operation: Add one element at top of stack


2. Special Push Operation: Create a new stack of size greater than old stack (according to one of the strategy above)
and copy all elements from old stack and then push the new element to the new stack.

Q. 2 Can the Tower of Hanoi problem solve using recursion? Explain by taking an example.
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to
move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a
disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Take an example for 2 disks :
Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Step 1 : Shift first disk from 'A' to 'B'.


Step 2 : Shift second disk from 'A' to 'C'.
Step 3 : Shift first disk from 'B' to 'C'.

The pattern here is :


Shift 'n-1' disks from 'A' to 'B'.
Shift last disk from 'A' to 'C'.
Shift 'n-1' disks from 'B' to 'C'.

Image illustration for 3 disks :

Q. 3 Explain Algorithm for Multiple stack implementation using single array


Implement two stacks in an array

Create a data structure twoStacks that represents two stacks. Implementation of twoStacks should use only one array,
i.e., both stacks should use the same array for storing elements. Following functions must be supported
by twoStacks.
push1(int x) –> pushes x to first stack
push2(int x) –> pushes x to second stack
pop1() –> pops an element from first stack and return the popped element
pop2() –> pops an element from second stack and return the popped element
Method 1 (Divide the space in two halves)
A simple way to implement two stacks is to divide the array in two halves and assign the half half space to two
stacks, i.e., use arr[0] to arr[n/2] for stack1, and arr[(n/2) + 1] to arr[n-1] for stack2 where arr[] is the array to be used
to implement two stacks and size of array be n.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

The problem with this method is inefficient use of array space. A stack push operation may result in stack overflow
even if there is space available in arr[]. For example, say the array size is 6 and we push 3 elements to stack1 and do
not push anything to second stack2. When we push 4th element to stack1, there will be overflow even if we have
space for 3 more elements in array.
Method 2 (A space efficient implementation)
This method efficiently utilizes the available space. It doesn’t cause an overflow if there is space available in arr[].
The idea is to start two stacks from two extreme corners of arr[]. stack1 starts from the leftmost element, the first
element in stack1 is pushed at index 0. The stack2 starts from the rightmost corner, the first element in stack2 is
pushed at index (n-1). Both stacks grow (or shrink) in opposite direction. To check for overflow, all we need to
check is for space between top elements of both stacks. This check is highlighted in the below code.

Q. 4 Derive an algorithm which converts infix expression to its postfix expression. Also write algorithm which
evaluates the postfix expression.
Algorithm to convert Infix To Postfix

Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression Y.

1. Push “(“onto Stack, and add “)” to the end of X.


2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.
3. If an operand is encountered, add it to Y.
4. If a left parenthesis is encountered, push it onto Stack.
5. If an operator is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has the same
precedence as or higher precedence than operator.
2. Add operator to Stack.
[End of If]
6. If a right parenthesis is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left parenthesis is
encountered.
2. Remove the left Parenthesis.
[End of If]
[End of If]
7. END.

Algorithm for Evaluation of Postfix Expression

1. Create an empty stack and start scanning the postfix expression from left to right.
2. If the element is an operand, push it into the stack.
3. If the element is an operator O, pop twice and get A and B respectively. Calculate BOA and push it
back to the stack.
4. When the expression is ended, the value in the stack is the final answer.

Q. 5 (a)Convert this infix into postfix and prefix: A*(B/C*D)+E


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q. 5(b) Evaluate this Postfix expression: 729*+


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Unit 2:
Short Answers: (2 Marks Each)

Q. 1 Write difference between Queue and Linked list?

Queue Singly Linked List

A linked list is a collection of one or more


Queue is a collection of one or more elements arranged in
elements arranged in memory in a dis-contiguous
memory in a contiguous fashion.
fashion.

Static Queue is always fixed size. List size is never fixed.

In Queue, only one and single type of information is stored List also stored the address for the next node
because static Queue implementation is through Array. along with it’s content.

Static Queue is index based. Singly linked list is reference based.

Insertion can always be performed on a single end called Insertion as well as deletion can performed any
REAR and deletion on the other end called FRONT. where within the list.

Queue is always based on FIFO. List may be based on FIFI or LIFO etc.

While List has only one pointer basically called


Queue have two pointer FRONT and REAR.
HEAD.

Q. 2 How will you use Linked List for multiplication of polynomials.

Polynomial Multiplication Using Linked List


A polynomial expression can be represent as linked list. 4X^4 + 3x^2 + 7X is a polynomial expression and its linked
list representation is as follows.

+------------+ +-----------+ +---------------+


| 4 | 4 | -|--->| 3 | 2 | -|--->| 7 | 1 | NULL|
+------------+ +-----------+ +----------------+

Here, each node composed of co-efficient, exponent and a pointer to the next node.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Multiplication of polynomial expressions:


3X^3 + 4x^2 + 5X
X^4

Output is 3x^7 + 4X^6 + 5X^4

Q. 3 Explain round robin algorithm by taking an example.

Round robin scheduling is the preemptive scheduling in which every process get executed in a cyclic way, i.e. in this a
particular time slice is allotted to each process which is known as time quantum. Every process, which is present in the
queue for processing, CPU is assigned to that process for that time quantum. Now, if the execution of the process gets
completed in that time quantum, then the process will get terminate otherwise the process will again go to the ready
queue, and the previous process will wait for the turn to complete its execution.

The scheduling drives its name from the principle which is known as a round robin in which every person takes an equal
share of anything they have in turn. We make use of round robin scheduling algorithm in a time-sharing system. It is
generally used by those operating systems which has multiple clients to make use of resources.
Example of Round Robin Scheduling

In this example, we will take six processes P1, P2, P3, P4, P5 and P6 whose arrival and burst time are given in the table.
The time quantum is 4 units.

Processes Arrival Time Burst Time

P1 0 5

P2 1 6

P3 2 3

P5 3 1

P6 4 5

P7 5 4

Now we have to maintain the ready queue and gantt chart in the algorithm again and again as their structures get
changed after every scheduling.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Ready Queue
Initially, at time 0, the process P1 will be executed for the 4 units of time quantum. So, in the starting in ready queue,
there will be only one process P1.

P1

Gantt chart

P1 will be executed for 4 units.

Ready Queue
Midwhile, during the execution of process P1, some other processes like P2, P3,P4 and P5 arises for the execution in the
ready queue. As we know P1 has not completed since its time is 5 and we have 4 units of time slice. So, 1 unit is still
left. So it will be again added at the back in ready queue.

P2 P3 P4 P5 P1
6 3 1 5 1

GANTT chart
Now the gantt chart will be like this.

Ready queue
During the execution time of P2, another process P6 arrives in the ready queue. Also, we know that P2 has not
completed yet as its 2 units of burst time is still left. So, again we will add P2 in the ready queue at the back.

P3 P4 P5 P1 P6 P2
3 1 5 1 4 2

GANTT CHART
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Now, P3 will be executed for 3 units of time slice as its bursts time is 3 units.

Ready queue
Now the process P3 is completed in the time slice of 4 units. So, we will not add P3 in the ready queue and now we will
execute the next process P4.

P4 P5 P6 P1 P2
1 5 1 4 2

GANTT CHART

Ready queue
The next process in the queue is P5 which has 5 units of bursts time. Again, the process P4 gets completed as it has only
1 unit of bursts time.

P5 P6 P1 P2
5 1 4 2

GANTT chart

Ready Queue
Now the process has not completed as 1 unit of burst time is left. So we add it in the ready queue in the back.

P1 P6 P2 P5
1 4 2 1

GANTT chart
Now the process P1 will be executed so that it can complete its execution as its turn has come. As we know it requires
only 1 unit of bursts time, so it will get completed.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Ready queue
As P1 also get completed. So , we will not add it to the ready queue. Now only three processes are left which are P6, P2
and P5.

P6 P2 P5
4 2 1

GANTT CHART
Now P6 has units of 4 units of bursts time. So it will get executed in 4 units of time slice.

Ready queue
Since P6 is executed completely. so, we will not add it to the ready queue. Now only 2 processes left in the ready queue
which are P2 and P5.

P2 P5
2 1

GANTT CHART
Now P2 will be executed again and it requires only 2 units of bursts time. So now it will be completed.

Ready queue
Only process left in the ready queue is P5 which requires only 1 unit of bursts time. As we know our time slice is of 4
units. So it will get completed in the next burst.

P5
1
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

GANTT CHART
The process P5 will get executed until it get completed as it is the only process left in the ready queue.

Now we will calculate turn around time, completion time and average waiting time which is shown in the below table.
Turn around time= completion time- arrival time
Waiting time= turn around time – burst time

Average waiting time= (12+16+6+8+15+11)/6= 76/6 = 12.66 units

Advantages of round robin scheduling

• It is simple.
• It is easy to implement.
• It deals with all process without any priority.
• In this, all jobs get easily allocated to CPU.
• Like first come first serve scheduling, in this no problem of convoy effect or starvation is there.
• Round robin scheduling does not depend upon burst time. So it can be easily implementable on the system.

Disadvantages of round robin scheduling

• Since round robin scheduling depends upon time quantum. So deciding a perfect time quantum for scheduling is a very
difficult task.
• If the time quantum is higher, then the response time of the system will also be higher.
• If the time quantum is lower, then there is higher context switching overhead.

Q. 4 What are Advantages and Disadvantages of Linked List


Advantages and Disadvantages of Linked List
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Advantages of Linked List

Dynamic Data Structure

Linked list is a dynamic data structure so it can grow and shrink at runtime by allocating and deallocating memeory. So
there is no need to give initial size of linked list.

Insertion and Deletion

Insertion and deletion of nodes are really easier. Unlike array here we don’t have to shift elements after insertion or
deletion of an element. In linked list we just have to update the address present in next pointer of a node.

No Memory Wastage

As size of linked list can increase or decrease at run time so there is no memory wastage. In case of array there is lot of
memory wastage, like if we declare an array of size 10 and store only 6 elements in it then space of 4 elements are
wasted. There is no such problem in linked list as memory is allocated only when required.

Implementation

Data structures such as stack and queues can be easily implemented using linked list.

Disadvantages of Linked List

Memory Usage

More memory is required to store elements in linked list as compared to array. Because in linked list each node contains
a pointer and it requires extra memory for itself.

Traversal

Elements or nodes traversal is difficult in linked list. We can not randomly access any element as we do in array by
index. For example if we want to access a node at position n then we have to traverse all the nodes before it. So, time
required to access a node is large.

Reverse Traversing

In linked list reverse traversing is really difficult. In case of doubly linked list its easier but extra memory is required for
back pointer hence wastage of memory.

If you know some other advantages and disadvantages of linked list then please mention by commenting below.

Q. 5 Represent priority queue by linked list &Array.


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Using Array: A simple implementation is to use array of following structure.


struct item {
int item;
int priority;
}

insert() operation can be implemented by adding an item at end of array in O(1) time.

getHighestPriority() operation can be implemented by linearly searching the highest priority item in array. This
operation takes O(n) time.

deleteHighestPriority() operation can be implemented by first linearly searching an item, then removing the item by
moving all subsequent items one position back.

Linked Representation:-

Pre-requisite

Linked Lists, Priority Queues

The list is so created so that the highest priority element is always at the head of the list. The list is arranged in
descending order of elements based on their priority. This allow us to remove the highest priority element in O(1) time.
To insert an element we must traverse the list and find the proper position to insert the node so that the overall order of
the priority queue is maintained. This makes the push() operation takes O(N) time. The pop() and peek() operations are
performed in constant time.

Algorithm :
PUSH(HEAD, DATA, PRIORITY)
Step 1: Create new node with DATA and PRIORITY
Step 2: Check if HEAD has lower priority. If true follow Steps 3-4 and end. Else goto Step 5.
Step 3: NEW -> NEXT = HEAD
Step 4: HEAD = NEW
Step 5: Set TEMP to head of the list
Step 6: While TEMP -> NEXT != NULL and TEMP -> NEXT -> PRIORITY > PRIORITY
Step 7: TEMP = TEMP -> NEXT
[END OF LOOP]
Step 8: NEW -> NEXT = TEMP -> NEXT
Step 9: TEMP -> NEXT = NEW
Step 10: End

POP(HEAD)
Step 2: Set the head of the list to the next node in the list. HEAD = HEAD -> NEXT.
Step 3: Free the node at the head of the list
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Step 4: End

PEEK(HEAD):
Step 1: Return HEAD -> DATA
Step 2: End

Q. 6 What are applications of Queue and Linked list.

Applications of Queue data structure

• Queue is useful in CPU scheduling, Disk Scheduling. When multiple processes require CPU at the same time,
various CPU scheduling algorithms are used which are implemented using Queue data structure.
• When data is transferred asynchronously between two processes. Queue is used for synchronization. Examples :
IO Buffers, pipes, file IO, etc.
• In print spooling, documents are loaded into a buffer and then the printer pulls them off the buffer at its own rate.
Spooling also lets you place a number of print jobs on a queue instead of waiting for each one to finish before
specifying the next one.
• Breadth First search in a Graph .It is an algorithm for traversing or searching graph data structures. It starts at
some arbitrary node of a graph and explores the neighbor nodes first, before moving to the next level neighbors.
This Algorithm uses Queue data structure.
• Handling of interrupts in real-time systems. The interrupts are handled in the same order as they arrive, First
come first served.
• In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until a service
representative is free.

Applications of linked list in computer science –

1. Implementation of stacks and queues


2. Implementation of graphs : Adjacency list representation of graphs is most popular which is uses linked list to
store adjacent vertices.
3. Dynamic memory allocation : We use linked list of free blocks.
4. Maintaining directory of names
5. Performing arithmetic operations on long integers
6. Manipulation of polynomials by storing constants in the node of linked list
7. representing sparse matrices

Applications of linked list in real world-

1. Image viewer – Previous and next images are linked, hence can be accessed by next and previous button.
2. Previous and next page in web browser – We can access previous and next url searched in web browser by
pressing back and next button since, they are linked as linked list.
3. Music Player – Songs in music player are linked to previous and next song. you can play songs either from
starting or ending of the list.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Descriptive Answers: (5 to 20 Marks)


Q. 1 Write an algorithm to Enqueue and Dequeue in Circular Queue?

The queue is considered as a circular queue when the positions 0 and MAX-1 are adjacent. Any position before front is
also after rear.

Note that the container of items is an array. Array is stored in main memory. Main memory is linear. So this circularity
is only logical. There can not be physical circularity in main memory.

Consider the example with Circular Queue implementation

See the logical circularity of the queue. Addition causes the increment in REAR. It means that when REAR reaches
MAX-1 position then Increment in REAR causes REAR to reach at first position that is 0.

if( rear == MAX -1)


rear = 0;
else
rear = rear + 1;

The short-hand equivalent representation may be

1rear = ( rear + 1) % MAX;


As we know that, Deletion causes the increment in FRONT. It means that when FRONT reaches the MAX-1 position,
then increment in FRONT, causes FRONT to reach at first position that is 0.
1if( front == MAX -1 )
2 front = 0;
3else
4 front = front + 1;
The short-hand equivalent representation may be
1front = ( front + 1) % MAX;
Drawback of Circular Queue
The drawback of circular queue is , difficult to distinguished the full and empty cases. It is also known as boundary case
problem.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

In circular queue it is necessary that:


Before insertion, fullness of Queue must be checked (for overflow).
Before deletion, emptiness of Queue must be checked (for underflow).

Condition to check FULL Circular Queue

1if( ( front == MAX-1) || ( front ==0 && rear == MAX -1 ) )

Condition to check EMPTY Circular Queue


1if( ( front == MAX-1) || ( front ==0 && rear == MAX -1 ) )

Solution of the drawback of circular Queue

Use count variable to hold the current position ( in case of insertion or deletion).

Operation of Circular Queue using count

Initialize Operation.
Is_Full check.
Is_Empty check.
Addition or Insertion operation.
Deletion operation.

Algorithms

INIT(QUEUE,FRONT,REAR,COUNT)
INSERT-ITEM(QUEUE, FRONT, REAR, MAX, COUNT, ITEM)
REMOVE-ITEM(QUEUE, FRONT, REAR, COUNT, ITEM)
FULL-CHECK(QUEUE,FRONT,REAR,MAX,COUNT,FULL)
EMPTY-CHECK(QUEUE,FRONT,REAR,MAX,COUNT,EMPTY)
INIT(QUEUE,FORNT,REAR,COUNT)
This algorithm is used to initialize circular queue.
1. FRONT := 1;
2. REAR := 0;
3. COUNT := 0;
4. Return;

INSERT-ITEM( QUEUE, FRONT, REAR, MAX, COUNT, ITEM)


This algorithm is used to insert or add item
into circular queue.
1. If ( COUNT = MAX ) then
a. Display “Queue overflow”;
b. Return;
2. Otherwise
a. If ( REAR = MAX ) then
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

i. REAR := 1;
b. Otherwise
i. REAR := REAR + 1;
c. QUEUE(REAR) := ITEM;
d. COUNT := COUNT + 1;
3. Return;

REMOVE-ITEM( QUEUE, FRONT, REAR, COUNT, ITEM)


This algorithm is used to remove or delete item
from circular queue.
1. If ( COUNT = 0 ) then
a. Display “Queue underflow”;
b. Return;
2. Otherwise
a. ITEM := QUEUE(FRONT)l
b. If ( FRONT =MAX ) then
i. FRONT := 1;
c. Otherwise
i. FRONT := FRONT + 1;
d. COUNT := COUNT + 1;
3. Return;

EMPTY-CHECK(QUEUE,FRONT,REAR,MAX,COUNT,EMPTY)
This is used to check queue is empty or not.
1. If( COUNT = 0 ) then
a. EMPTY := true;
2. Otherwise
a. EMPTY := false;
3. Return ;

FULL-CHECK(QUEUE,FRONT,REAR,MAX,COUNT,FULL)
This algorithm is used to check queue is full or not.
1. If ( COUNT = MAX ) then
a. FULL := true;
2. Otherwise
a. FULL := false;
3. Return ;

Q. 2 Write an algorithm to Enqueue and Dequeue in Circular Linked List.

Insertion in an empty List


Initially when the list is empty, last pointer will be NULL
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

After inserting a node T

After insertion, T is the last node so pointer last points to node T. And Node T is first and last node, so T is pointing to itself.

Insertion at the beginning of the list


To Insert a node at the beginning of the list, follow these step:
1. Create a node, say T.
2. Make T -> next = last -> next.
3. last -> next = T.

After insertion,
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Insertion at the end of the list


To Insert a node at the end of the list, follow these step:
1. Create a node, say T.
2. Make T -> next = last -> next;
3. last -> next = T.
4. last = T.

After insertion,

Insertion in between the nodes


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

To Insert a node at the end of the list, follow these step:


1. Create a node, say T.
2. Search the node after which T need to be insert, say that node be P.
3. Make T -> next = P -> next;
4. P -> next = T.

Suppose 12 need to be insert after node having value 10,

After searching and insertion,

Deletion from circular linked list

Algorithm

Case 1: List is empty.

• If the list is empty we will simply return.

Case 2:List is not empty

• If the list is not empty then we define two pointers curr and prev and initialize the pointer curr with the head
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

node.
• Traverse the list using curr to find the node to be deleted and before moving curr to next node, everytime set
prev = curr.
• If the node is found, check if it is the only node in the list. If yes, set head = NULL and free(curr).
• If the list has more than one node, check if it is the first node of the list. Condition to check this( curr == head). If
yes, then move prev until it reaches the last node. After prev reaches the last node, set head = head -> next and
prev -> next = head. Delete curr.
• If curr is not first node, we check if it is the last node in the list. Condition to check this is (curr -> next == head).
• If curr is the last node. Set prev -> next = head and delete the node curr by free(curr).
• If the node to be deleted is neither the first node nor the last node, then set prev -> next = temp -> next and delete
curr.

Q. 3 Write an algorithm to Enqueue and Dequeue in DeQueue.

A double ended queue also called as deque (pronounced as ‘deck’ or ‘dequeue’) is a list in which the elements can
be inserted or deleted at either end in constant time. It is also known as a head-tail linked list because elements can be
added to or removed from either the front (head) or the back (tail) end. However, no element can be added and deleted
from the middle. In the computer’s memory, 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.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

There are two variants of a double-ended queue. They include:

• Input restricted deque: In this dequeue,insertions can be done only at one of the ends,while deletions can be
done from both ends.
• Output restricted deque: In this dequeue,deletions can be done only at one of the ends,while insertions can be
done on both ends.

Algorithm for Insertion at rear end

Step-1: [Check for overflow]


if(rear==MAX)
Print("Queue is Overflow”);
return;
Step-2: [Insert Element]
else
rear=rear+1;
q[rear]=no;
[Set rear and front pointer]
if rear=0
rear=1;
if front=0
front=1;
Step-3: return
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Algorithm for Insertion at front end

Step-1 : [Check for the front position]


if(front<=1)
Print("Cannot add item at the front”);
return;
Step-2 : [Insert at front]
else
front=front-1;
q[front]=no;
Step-3 : Return
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Algorithm for Deletion from front end

Step-1 [ Check for front pointer]


if front=0
print(" Queue is Underflow”);
return;
Step-2 [Perform deletion]
else
no=q[front];
print(“Deleted element is”,no);
[Set front and rear pointer]
if front=rear
front=0;
rear=0;
else
front=front+1;
Step-3 : Return

Algorithm for Deletion from rear end

Step-1 : [Check for the rear pointer]


if rear=0
print(“Cannot delete value at rear end”);
return;
Step-2: [ perform deletion]
else
no=q[rear];
[Check for the front and rear pointer]
if front= rear
front=0;
rear=0;
else
rear=rear-1;
print(“Deleted element is”,no);
Step-3 : Return
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Complexity

• Insertion or deletion in the middle is O(n)


• The time complexity of random access by index is O(1)
• time complexity of all enque(insert)/deque(delete) operations is O(1)

Q. 4 Write an algorithm to Implement Queue using Stack

Our objective is to implement queue using stacks.

Approach:

• Take 2 Stacks, stack1 and stack2.


• stack1 will be used a back of the Queue and stack2 will be used as front of the Queue.
• Push() operation will be done on stack1, and peek() and pop() operations will be done on stack2.
• When peek() and pop() are called, check is stack2 is empty, if yes then move all the elements from stack1 and
push them into stack2.

Example
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q. 5 Discuss Head node in linked List with suitable Example.

Header Nodes.

A header linked list is a linked list which always contains a special node called the header node at the beginning of the
list. It is an extra node kept at the front of a list. Such a node does not represent an item in the list.

Grounded header list : is a header list where the last node contain the null pointer.

Circular header list : is a header list where the last node points back to the header node.

Header nodes can contain information about the Link List , such as number of total nodes, supposing link list contains
information of employees in a company the header node can contain total number of employees in the company
(included in link list) , total salary of all the employees min and max salary etc. The information can be processed as the
nodes are added or deleted so that information can be extracted from the header node and we need not process the linked
list every time when we need it. Its usefulness can be decided depending upon the system requirement. Header node can
be made as use full a required.

The header node has structure different from normal node. In a typical program given below( Program can be improved
in quality and performance) as required. When ever node is added total , min and max value are updated. In the display
we get information about the header node and all the nodes. This can be modified having two display functions one for
header node and one for other nodes.

Q. 6 What is doubly linked list? Explain the algorithms for inserting a node and deleting a node from a doubly
linked list.

Doubly linked list is a type of linked list in which each node apart from storing its data has two links. The first link
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

points to the previous node in the list and the second link points to the next node in the list. The first node of the list has
its previous link pointing to NULL similarly the last node of the list has its next node pointing to NULL.

Algorithm to insert node at the beginning of a Doubly linked list


Algorithm to insert a node at the beginning of a Doubly linked list
%% Input : head {A pointer pointing to the first node of the list}
Begin:
alloc (newNode)
If (newNode == NULL) then
write ('Unable to allocate memory')
End if
Else then
read (data)
newNode.data ← data;
newNode.prev ← NULL;
newNode.next ← head;

head.prev ← newNode;
head ← newNode;
write('Node added successfully at the beginning of List')
End else
End
Algorithm to insert node at the end of a Doubly linked list
Algorithm to insert a node at the end of Doubly linked list
%% Input : last {Pointer to the last node of doubly linked list}
Begin:
alloc (newNode)
If (newNode == NULL) then
write ('Unable to allocate memory')
End if
Else then
read (data)
newNode.data ← data;
newNode.next ← NULL;
newNode.prev ← last;

last.next ← newNode;
last ← newNode;
write ('Node added successfully at the end of List')
End else
End
Algorithm to insert node at any position of a Doubly linked list
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Algorithm to insert node at any position of doubly linked list


%% Input : head {Pointer to the first node of doubly linked list}
: last {Pointer to the last node of doubly linked list}
: N {Position where node is to be inserted}
Begin:
temp ← head
For i←1 to N-1 do
If (temp == NULL) then
break
End if
temp ← temp.next;
End for
If (N == 1) then
insertAtBeginning()
End if
Else If (temp == last) then
insertAtEnd()
End if
Else If (temp != NULL) then
alloc (newNode)
read (data)

newNode.data ← data;
newNode.next ← temp.next
newNode.prev ← temp
If (temp.next != NULL) then
temp.next.prev ← newNode;
End if
temp.next ← newNode;
write('Node added successfully')
End if
End

Algorithm to delete node from beginning of a doubly linked list


Algorithm to delete node from beginning
%% Input: head {Pointer to first node of the linked list}
Begin:
If (head == NULL) then
write ('Can't delete from an empty list')
End if
Else then
toDelete ← head;
head ← head.next;
head.prev ← NULL;
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

unalloc (toDelete)
write ('Successfully deleted first node from the list')
End if
End
Algorithm to delete node from end of a doubly linked list
Algorithm to delete node from end
%% Input: last {Pointer to last node of the linked list}
Begin:
If (last == NULL) then
write ('Can't delete from an empty list')
End if
Else then
toDelete ← last;
last ← last.prev;
last.next ← NULL;
unalloc (toDelete)
write ('Successfully deleted last node from the list')

End if
End
Algorithm to delete node from any position of a doubly linked list
Algorithm to delete node from any position
%% Input : head {Pointer to the first node of the list}
last {Pointer to the last node of the list}
N {Position to be deleted from list}
Begin:
current ← head;
For i ← 1 to N and current != NULL do
current ← current.next;
End for
If (N == 1) then
deleteFromBeginning()
End if
Else if (current == last) then
deleteFromEnd()
End if
Else if (current != NULL) then
current.prev.next ← current.next
If (current.next != NULL) then
current.next.prev ← current.prev;
End if
unalloc (current)
write ('Node deleted successfully from ', N, ' position')
End if
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Else then
write ('Invalid position')
End if
End
Steps to delete node from any position of a doubly linked list

Let us suppose that we want to delete node from 2nd position.

1. Traverse to Nth node of the linked list, lets say a pointer current points to Nth node in our case 2 node.

2. Link the node behind current node with the node ahead of current node, which means now the N-1th node will
point to N+1th node of the list. Which can be implemented as current->prev->next = current->next.

3. If N+1th node is not NULL then link the N+1th node with N-1th node i.e. now the previous address field of N+1th
node will point to N-1th node. Which can be implemented as current->next->prev = current->prev.

4. Finally delete the current node from memory and you are done.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q.7.Write an algorithm to count no of nodes and reverse a linked list?

Count no of nodes

Iterative Solution

1) Initialize count as 0
2) Initialize a node pointer, current = head.
3) Do following while current is not NULL
a) current = current -> next
b) count++;
4) Return count

Reverse a linked list

Iterative Method

1. Initialize three pointers prev as NULL, curr as head and next as NULL.
2. Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next

// Now change next of current


// This is where actual reversing happens
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

curr->next = prev

// Move prev and curr one step forward


prev = curr
curr = next

Unit 3:
Short Answers: (2 Marks Each)

Q. 1 Write Difference among Bubble sort, insertion sort and Selection sort .

Bubble Sort - It is a sorting algorithm in which two adjacent elements of an array are checked and swapped if they are in
wrong order and this process is repeated until we get a sorted array.

In this first two elements of the array are checked and swapped if they are in wrong order. Then first and third elements
are checked and swapped if they are in wrong order. This continues till the lat element is checked and swapped if
necessary.

Selection Sort - It is also a sorting algorithm in which first step is to find the smallest element in the array. This smallest
element is swapped with the first element. After this, search for the smallest element in the sub array formed by
excluding the first element and compare it with the first element of the sub array. Repeat it till the array gets sorted.

Insertion Sort - In this, the second element is compared with the first element and is swapped if it is not in order.
Similarly, we take the third element in the next iteration and place it at the right place in the sub array of the first and
second elements (as the sub array containing the first and second elements is already sorted). We repeat this step with
the fourth element of the array in the next iteration and place it at the right position in the sub array containing the first,
second and the third elements. We repeat this process until our array gets sorted.

Q. 2 Write Difference between Merge sort and Quick sort.


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Descriptive Answers: (5 to 20 Marks)


Q. 1 Sort the following data in ascending order using Quick sort : 9,4.12,6, 5,10,7

Q. 2 Write an algorithm for merge sort and comment on its complexity.

merge sort
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity being

Ο(n log n), it is one of the most respected algorithms.

Merge sort first divides the array into equal halves and then combines them in a sorted manner.

Algorithm

Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one
element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list sorted too.

Step 1 − if it is only one element in the list it is already sorted, return.


Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order.

How Merge Sort Works?

To understand merge sort, we take an unsorted array as the following −

We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are
achieved. We see here that an array of 8 items is divided into two arrays of size 4.

This does not change the sequence of appearance of items in the original. Now we divide these two arrays into halves.

We further divide these arrays and we achieve atomic value which can no more be divided.

Now, we combine them in exactly the same manner as they were broken down. Please note the color codes given to
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

these lists.

We first compare the element for each list and then combine them into another list in a sorted manner. We see that 14
and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values we put 10 first, followed by 27.
We change the order of 19 and 35 whereas 42 and 44 are placed sequentially.

In the next iteration of the combining phase, we compare lists of two data values, and merge them into a list of found
data values placing all in a sorted order.

After the final merging, the list should look like this −

Q. 3 What is difference between internal sorting and External sorting.

In internal sorting all the data to sort is stored in memory at all times while sorting is in progress. In external sorting data
is stored outside memory (like on disk) and only loaded into memory in small chunks. External sorting is usually
applied in cases when data can't fit into memory entirely.

So in internal sorting you can do something like shell sort - just access whatever array elements you want at whatever
moment you want. You can't do that in external sorting - the array is not entirely in memory, so you can't just randomly
access any element in memory and accessing it randomly on disk is usually extremely slow. The external sorting
algorithm has to deal with loading and unloading chunks of data in optimal manner.

Q. 4 Write short note on Radix Sort and Topological Sort?

Radix Sort

Radix sort is a small method that many people intuitively use when alphabetizing a large list of names. Specifically, the
list of names is first sorted according to the first letter of each name, that is, the names are arranged in 26 classes.

Intuitively, one might want to sort numbers on their most significant digit. However, Radix sort works counter-
intuitively by sorting on the least significant digits first. On the first pass, all the numbers are sorted on the least
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

significant digit and combined in an array. Then on the second pass, the entire numbers are sorted again on the second
least significant digits and combined in an array and so on.

Algorithm: Radix-Sort (list, n)


shift = 1
for loop = 1 to keysize do
for entry = 1 to n do
bucketnumber = (list[entry].key / shift) mod 10
append (bucket[bucketnumber], list[entry])
list = combinebuckets()
shift = shift * 10

Analysis

Each key is looked at once for each digit (or letter if the keys are alphabetic) of the longest key. Hence, if the longest
key has m digits and there are n keys, radix sort has order O(m.n).

However, if we look at these two values, the size of the keys will be relatively small when compared to the number of
keys. For example, if we have six-digit keys, we could have a million different records.

Here, we see that the size of the keys is not significant, and this algorithm is of linear complexity O(n)

Topological sorting

Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge
uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.

For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological
sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The first vertex in
topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges).
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q. 5 Write algorithms to sort real numbers using insertion sort and selection sort.

insertion sort

This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For
example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list,
has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort.

The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array).
This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n 2), where n is the
number of items.

Now we have a bigger picture of how this sorting technique works, so we can derive simple steps by which we can
achieve insertion sort.

Step 1 − If it is the first element, it is already sorted. return 1;


Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

selection sort

Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which
the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted
part is empty and the unsorted part is the entire list.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element
becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.

This algorithm is not suitable for large data sets as its average and worst case complexities are of Ο(n 2), where n is the
number of items.

Algorithm
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted

Q. 6 Write algorithm for Bubble sort. Sort the following list by your algorithm:-
73,49, 53, 12,48,10,84,70,20,16

Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of
adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for
large data sets as its average and worst case complexity are of Ο(n2) where n is the number of items.
Algorithm

We assume list is an array of n elements. We further assume that swap function swaps the values of the given array
elements.

begin BubbleSort(list)

for all elements of list


if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for

return list

end BubbleSort

Q.7Explain Count sort algorithm by taking an appropriate example.

Counting Sort
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects
having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the
output sequence.

Let us understand it with the help of an example.

For simplicity, consider the data in the range 0 to 9.


Input data: 1, 4, 1, 2, 7, 5, 2
1) Take a count array to store the count of each unique object.
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 2 2 0 1 1 0 1 0 0

2) Modify the count array such that each element at each index
stores the sum of previous counts.
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 2 4 4 5 6 6 7 7 7

The modified count array indicates the position of each object in


the output sequence.

3) Output each object from the input sequence followed by


decreasing its count by 1.
Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 2.
Put data 1 at index 2 in output. Decrease count by 1 to place
next data 1 at an index 1 smaller than this index.
Points to be noted:
1. Counting sort is efficient if the range of input data is not significantly greater than the number of objects to be sorted.
Consider the situation where the input sequence is between range 1 to 10K and the data is 10, 5, 10K, 5K.
2. It is not a comparison based sorting. It running time complexity is O(n) with space proportional to the range of data.
3. It is often used as a sub-routine to another sorting algorithm like radix sort.
4. Counting sort uses a partial hashing to count the occurrence of the data object in O(1).
5. Counting sort can be extended to work for negative inputs also.

Unit 4:
Short Answers: (2 Marks Each)

Q. 1 Explain following:
Terminology used in Tree
B Tree
Complete Binary Tree
Extended Binary Tree.

A B-tree is a tree data structure that keeps data sorted and allows searches, insertions, and deletions in logarithmic
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

amortized time. Unlike self-balancing binary search trees, it is optimized for systems that read and write large blocks of
data. It is most commonly used in database and file systems.

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes

are as far left as possible.

An extended binary tree is a transformation of any binary tree into a complete binary tree. This transformation consists
of replacing every null subtree of the original tree with “special nodes.” The nodes from the original tree are then
internal nodes, while the “special nodes” are external nodes.

Q. 2 How a binary tree can be represented in memory. Explain with example.

Binary Tree Representations

A binary tree data structure is represented using two methods. Those methods are as follows...

1. Array Representation
2. Linked List Representation

Consider the following binary tree...

1. Array Representation of Binary Tree

In array representation of a binary tree, we use one-dimensional array (1-D Array) to represent a binary tree.
Consider the above example of a binary tree and it is represented as follows...
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

To represent a binary tree of depth 'n' using array representation, we need one dimensional array with a maximum size
of 2n + 1.

2. Linked List Representation of Binary Tree

We use a double linked list to represent a binary tree. In a double linked list, every node consists of three fields. First
field for storing left child address, second for storing actual data and third for storing right child address.
In this linked list representation, a node has the following structure...

The above example of the binary tree represented using Linked list representation is shown as follows...

Q. 3 Explain Binary Search Tree and its disadvantage.


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Binary Search Tree is a node-based binary tree data structure which has the following properties:

• The left subtree of a node contains only nodes with keys lesser than the node’s key.
• The right subtree of a node contains only nodes with keys greater than the node’s key.
• The left and right subtree each must also be a binary search tree.

Disadvantages of using BST:

• The main disadvantage is that we should always implement a balanced binary search tree - AVL tree, Red-Black
tree, Splay tree. Otherwise the cost of operations may not be logarithmic and degenerate into a linear search on
an array.

Q. 4 What are different tree traversing approaches. Explain the need of threading.

Trees can be traversed in several ways:

Pre Order Traversal: Root, Left, Right.


In Order Traversal: Left, Root, Right.

Post Order Traversal: Left, Right, Root.

Level Order Traversal, also known as Breadth-first search.

The threads are useful for fast accessing ancestors of a node.

Q. 5 What do you understand with m-way tree. What is the difference between B tree and B+ tree.

The m-way search trees are multi-way trees which are generalised versions of binary trees where each node contains
multiple elements. In an m-Way tree of order m, each node contains a maximum of m – 1 elements and m children.

The goal of m-Way search tree of height h calls for O(h) no. of accesses for an insert/delete/retrieval operation. Hence, it
ensures that the height h is close to log_m(n + 1).

The difference between B-tree and B+ tree

• The nodes in the B+ tree do not store data, and all data stored in the leaf nodes causes the query time complexity
to be fixed to log n.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

• The B-tree query time complexity is not fixed, and is related to the position of the key in the tree, preferably
O(1).
• The B+ leaf nodes are connected in pairs, which can greatly increase the interval accessibility, and can be used in

range query.

• B-tree Each node key and data together, can not find the interval.
• The B+ tree is more suitable for external storage (storing disk data). Since the inner nodes have no data fields,
each node can index a larger and more precise range.

Q. 6 What are the different rotations can be performed on AVL Tree to make it balance. Explain all with
example.
AVL Rotations

To balance itself, an AVL tree may perform the following four kinds of rotations −

• Left rotation
• Right rotation
• Left-Right rotation
• Right-Left rotation

The first two rotations are single rotations and the next two rotations are double rotations. To have an unbalanced tree,
we at least need a tree of height 2. With this simple tree, let's understand them one by one.

Left Rotation

If a tree becomes unbalanced, when a node is inserted into the right subtree of the right subtree, then we perform a single
left rotation −

In our example, node A has become unbalanced as a node is inserted in the right subtree of A's right subtree. We
perform the left rotation by making A the left-subtree of B.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Right Rotation

AVL tree may become unbalanced, if a node is inserted in the left subtree of the left subtree. The tree then needs a right
rotation.

As depicted, the unbalanced node becomes the right child of its left child by performing a right rotation

Left-Right Rotation

Double rotations are slightly complex version of already explained versions of rotations. To understand them better, we
should take note of each action performed while rotation. Let's first check how to perform Left-Right rotation. A left-
right rotation is a combination of left rotation followed by right rotation.

State Action

A node has been inserted into the right subtree of the left
subtree. This makes C an unbalanced node. These scenarios
cause AVL tree to perform left-right rotation.

We first perform the left rotation on the left subtree of C. This


makes A, the left subtree of B.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Node C is still unbalanced, however now, it is because of the


left-subtree of the left-subtree.

We shall now right-rotate the tree, making B the new root node
of this subtree. C now becomes the right subtree of its own left
subtree.

The tree is now balanced.

Right-Left Rotation

The second type of double rotation is Right-Left Rotation. It is a combination of right rotation followed by left rotation.

State Action

A node has been inserted into the left subtree of the right subtree. This makes A, an
unbalanced node with balance factor 2.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

First, we perform the right rotation along C node, making C the right subtree of its
own left subtree B. Now, B becomes the right subtree of A.

Node A is still unbalanced because of the right subtree of its right subtree and
requires a left rotation.

A left rotation is performed by making B the new root node of the subtree. A
becomes the left subtree of its right subtree B.

The tree is now balance

Descriptive Answers: (5 to 20 Marks)


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q. 1 Construct a B Tree of order(2-3 tree) by inserting the following keys in the order shown into an empty B-
tree.
M,Q,A,N,P,W,X,T,G,E,J
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q. 2 A binary tree T has 9 nodes. The inorder and preorder traversals of T yield the following sequence of nodes:
Inorder: E,A,C,K,F,H,D,B,G
Preorder:F,A,E,K,C,D,H,G,B
Draw the tree T.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q. 3 What do you understand with AVL Tree.Create an AVL tree from the given set of values:
H,I,J,B,A,E,C,F,D,G,K,L

AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees
cannot be more than one for all nodes.
An Example Tree that is an AVL Tree

Why AVL Trees?


Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is the height of the BST.
The cost of these operations may become O(n) for a skewed Binary tree. If we make sure that height of the tree remains
O(Logn) after every insertion and deletion, then we can guarantee an upper bound of O(Logn) for all these operations.
The height of an AVL tree is always O(Logn) where n is the number of nodes in the tree
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q. 4 Write down the algorithm for INORDER traversal of a tree.

In-order
An in-order traversal on a tree performs the following steps starting from the root:

1) Traverse the left subtree by recursively calling the in-order function. 2) Return the root node value. 3) Traverse the
right subtree by recursively calling the in-order function.

Inorder Tree Traversal without Recursion


1) Create an empty stack S.
2) Initialize current node as root
3) Push the current node to S and set current = current->left until current is NULL
4) If current is NULL and stack is not empty then
a) Pop the top item from stack.
b) Print the popped item, set current = popped_item->right
c) Go to step 3.
5) If current is NULL and stack is empty then we are done.

Q. 5 Write down the algorithm for POSTORDER traversal of tree.

Postorder Traversal

Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.

Iterative Postorder Traversal


1.1 Create an empty stack
2.1 Do following while root is not NULL
a) Push root's right child and then root to stack.
b) Set root as root's left child.
2.2 Pop an item from stack and set it as root.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

a) If the popped item has a right child and the right child
is at top of stack, then remove the right child from stack,
push the root back and set root as root's right child.
b) Else print root's data and set root as NULL.
2.3 Repeat steps 2.1 and 2.2 while stack is not empty.

Q. 6 Write down the algorithm for inserting an element into B-Tree.

Inserting a key into a B-tree

Inserting a key k into a B-tree T of height h is done in a single pass down the tree, requiring O(h) disk accesses. The
CPU time required is O(th) = O(t logt n). The B-TREE-INSERT procedure uses B-TREE-SPLIT-CHILD to guarantee that the
recursion never descends to a full node.

Splitting the root with t = 4. Root node r is split in two, and a new root node s is created. The new root contains
the median key of r and has the two halves of r as children. The B-tree grows in height by one when the root is
split.

B-TREE-INSERT(T,k)
1 r root[T]
2 if n[r] = 2t - 1
3 then s ALLOCATE-NODE()
4 root[T] s
5 leaf[s] FALSE
6 n[s] 0
7 c1[s] r
8 B-TREE-SPLIT-CHILD(s,1,r)
9 B-TREE-INSERT-NONFULL(s,k)
10 else B-TREE-INSERT-NONFULL(r,k)
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Unit 5:
Short Answers: (2 Marks Each)

Q. 1 What is the difference between tree and graph. Can a tree be graph?Jusity.
Trees Graphs
Tree is special form of graph i.e. minimally In graph there can be more than one path
Path connected graph and having only one path between i.e. graph can have uni-directional or bi-
any two vertices. directional paths (edges) between nodes
Tree is a special case of graph having no loops, no Graph can have loops, circuits as well as
Loops
circuits and no self-loops. can have self-loops.
In tree there is exactly one root node and every child In graph there is no such concept of root
Root Node
have only one parent. node.
Parent Child In trees, there is parent child relationship so flow can In Graph there is no such parent child
relationship be there with direction top to bottom or vice versa. relationship.
Trees are less complex then graphs as having no Graphs are more complex in compare to
Complexity
cycles, no self-loops and still connected. trees as it can have cycles, loops etc
Tree traversal is a kind of special case of traversal of Graph is traversed by DFS: Depth First
Types of
graph. Tree is traversed in Pre-Order, In-Order and Search and in BFS : Breadth First
Traversal
Post-Order (all three in DFS or in BFS algorithm) Search algorithm
In graphs no such rules/ restrictions are
Connection In trees, there are many rules / restrictions for making
there for connecting the nodes through
Rules connections between nodes through edges.
edges.
Trees come in the category of DAG : Directed
DAG Acyclic Graphs is a kind of directed graph that have Graph can be Cyclic or Acyclic.
no cycles.
Different types of trees are : Binary Tree , Binary There are mainly two types of Graphs :
Different Types
Search Tree, AVL tree, Heaps. Directed and Undirected graphs.
Graph applications : Coloring of maps, in
Tree applications : sorting and searching like Tree
Applications OR (PERT & CPM), algorithms, Graph
Traversal & Binary Search.
coloring, job scheduling, etc.
In Graph, no. of edges depend on the
No. of edges Tree always has n-1 edges.
graph.
Model Tree is a hierarchical model. Graph is a network model.

Trees are graphs that do not contain even a single cycle. They represent hierarchical structure in a graphical form. Trees
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

belong to the simplest class of graphs. Despite their simplicity, they have a rich structure.

Q. 2 Explain graph, multigraph, NULL graph, isolated vertex, loop, degree, parallel edge.

A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as
vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be
defined as,

A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.

A multigraph is a graph that can have more than one edge between a pair of vertices.

The null graph is the graph which has no vertices.

That is, the null graph is the graph of order zero.

An isolated vertex is a vertex with degree zero; that is, a vertex that is not an endpoint of any edge.

In graph theory, a loop (also called a self-loop or a "buckle") is an edge that connects a vertex to itself. A simple graph
contains no loops.

Degree of Vertex

It is the number of vertices adjacent to a vertex V.

Notation − deg(V).

In a simple graph with n number of vertices, the degree of any vertices is −

deg(v) ≤ n – 1 ∀ v ∈ G

A vertex can form an edge with all other vertices except by itself. So the degree of a vertex will be up to the number
of vertices in the graph minus 1. This 1 is for the self-vertex as it cannot form a loop by itself. If there is a loop at
any of the vertices, then it is not a Simple Graph.

Degree of vertex can be considered under two cases of graphs −

• Undirected Graph
• Directed Graph

In graph theory, multiple edges (also called parallel edges or a multi-edge), are two or more edges that are incident to the
same two vertices. A simple graph has no multiple edges
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Q. 3 How you will categories graph. Explain.


There are various types of graphs depending upon the number of vertices, number of edges, interconnectivity, and
their overall structure.

We can categories it in directed and undirected, weighted and un-weighted.

There are various types of graphs such as Null Graph, Trivial Graph, Non-Directed Graph, Directed Graph, Simple
Graph, Connected Graph, Disconnected Graph, Regular Graph, Complete Graph, Cycle Graph, Wheel Graph, Cyclic
Graph, Acyclic Graph, Complete Bipartite Graph, Star Graph

.Q. 4 Explain the linked representation of a graph.

Linked Representation

In the linked representation, an adjacency list is used to store the Graph into the computer's memory.

Consider the undirected graph shown in the following figure and check the adjacency list representation.

An adjacency list is maintained for each node present in the graph which stores the node value and a pointer to the
next adjacent node to the respective node. If all the adjacent nodes are traversed then store the NULL in the pointer
field of last node of the list. The sum of the lengths of adjacency lists is equal to the twice of the number of edges
present in an undirected graph.

Consider the directed graph shown in the following figure and check the adjacency list representation of the graph.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

In a directed graph, the sum of lengths of all the adjacency lists is equal to the number of edges present in the graph.

In the case of weighted directed graph, each node contains an extra field that is called the weight of the node. The
adjacency list representation of a directed graph is shown in the following figure.

Q. 5 Why we use hashing. What are the different methods to evaluate hash function?
Hashing provides constant time search, insert and delete operations on average. This is why hashing is one of the
most used data structure, example problems are, distinct elements, counting frequencies of items, finding duplicates,
etc.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

here are various types of hash function which are used to place the data in a hash table,

Division method

Mid square method

Digit folding method

Q. 6 What do you understand with minimum spanning tree. What are different algorithms used to find
minimum spanning tree.

A spanning tree is a subset of Graph G, which has all the vertices covered with minimum possible number of edges.
Hence, a spanning tree does not have cycles and it cannot be disconnected..

By this definition, we can draw a conclusion that every connected and undirected Graph G has at least one spanning
tree. A disconnected graph does not have any spanning tree, as it cannot be spanned to all its vertices.

Minimum Spanning-Tree Algoriths

• Kruskal's Algorithm
• Prim's Algorithm

Both are greedy algorithms.

Descriptive Answers: (5 to 20 Marks)


Q. 1 Explain BFS algorithm with the help of example.

Breadth First Search:

The general idea behind breadth first traversal is that, start at a random vertex, then visit all of its neighbors, the first
vertex that we visit, say is at level ‘0’ and the neighbors are at level ‘1’. After visiting all the vertices at level ‘1’ we
then pick one of these vertexes at level ‘1’ and visit all its unvisited neighbors, we repeat this procedure for all other
vertices at level ‘1’. Say neighbors of level 1 are in level 2, now we will visit the neighbors of all the vertices at level
2, and this procedure will continue.

// algorithm for BFS()

Step1. Initialize all the vertices to ready state (STATUS = 1)


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Step2. Put the starting vertex into QUEUE and change its status to waiting (STATUS = 2)

Step 3: Repeat Step 4 and 5 until QUEUE is EMPTY

Step 4: Remove the front vertex from QUEUE, Process the vertex, Change its status to processed state (STATUS =
3)

Step 5: ADD all the neighbors in the ready state (STATUS = 1) to the RARE of the QUEUE and change their status
to waiting state (STATUS = 2)

Step 6: Exit.

Description of the Breadth First Search algorithm:


o Start at some node (e.g., node 0):

o
o Visit all the neighbors of node 0 first:
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

o
o Then visit the neighbors' neighbors:

o
o And so on

Q. 2 Explain DFS algorithm with the help of example.

Depth First Search:

The general idea behind depth first traversal is that, starting from any random vertex, single path is traversed until a
vertex is found whose all the neighbors are already been visited. The search then backtracks on the path until a vertex
with unvisited adjacent vertices is found and then begin traversing a new path starting from that vertex, and so on.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

This process will continue until all the vertices of the graph are visited.

//Algorithm for DFS()

Step1. Initialize all the vertices to ready state (STATUS = 1)

Step2. Put the starting vertex into STACK and change its status to waiting (STATUS = 2)

Step 3: Repeat Step 4 and 5 until STACK is EMPTY

Step 4: POP the top vertex from STACK, Process the vertex, Change its status to processed state (STATUS = 3)

Step 5: PUSH all the neighbors in the ready state (STATUS = 1) to the STACK and change their status to waiting
state (STATUS = 2)

Step 6: Exit.

The following image shows how DFS works.


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Time complexity O(V+E), when implemented using an adjacency list.

Q. 3 Explain Kruskal’s algorithm with the help of example.

Kruskal's algorithm to find the minimum cost spanning tree uses the greedy approach. This algorithm treats the graph
as a forest and every node it has as an individual tree. A tree connects to another only and only if, it has the least cost
among all available options and does not violate MST properties.

To understand Kruskal's algorithm let us consider the following example −

Step 1 - Remove all loops and Parallel Edges

Remove all loops and parallel edges from the given graph.

In case of parallel edges, keep the one which has the least cost associated and remove all others.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Step 2 - Arrange all edges in their increasing order of weight

The next step is to create a set of edges and weight, and arrange them in an ascending order of weightage (cost).

Step 3 - Add the edge which has the least weightage

Now we start adding edges to the graph beginning from the one which has the least weight. Throughout, we shall
keep checking that the spanning properties remain intact. In case, by adding one edge, the spanning tree property
does not hold then we shall consider not to include the edge in the graph.

The least cost is 2 and edges involved are B,D and D,T. We add them. Adding them does not violate spanning tree
properties, so we continue to our next edge selection.

Next cost is 3, and associated edges are A,C and C,D. We add them again −
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Next cost in the table is 4, and we observe that adding it will create a circuit in the graph. −

We ignore it. In the process we shall ignore/avoid all edges that create a circuit.

We observe that edges with cost 5 and 6 also create circuits. We ignore them and move on.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Now we are left with only one node to be added. Between the two least cost edges available 7 and 8, we shall add the
edge with cost 7.

By adding edge S,A we have included all the nodes of the graph and we now have minimum cost spanning tree.

Q. 4 Explain Prims algorithm with the help of example.

Prim's algorithm to find minimum cost spanning tree (as Kruskal's algorithm) uses the greedy approach. Prim's
algorithm shares a similarity with the shortest path first algorithms.

Prim's algorithm, in contrast with Kruskal's algorithm, treats the nodes as a single tree and keeps on adding new
nodes to the spanning tree from the given graph.

To contrast with Kruskal's algorithm and to understand Prim's algorithm better, we shall use the same example −

Step 1 - Remove all loops and parallel edges


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Remove all loops and parallel edges from the given graph. In case of parallel edges, keep the one which has the least
cost associated and remove all others.

Step 2 - Choose any arbitrary node as root node

In this case, we choose S node as the root node of Prim's spanning tree. This node is arbitrarily chosen, so any node
can be the root node. One may wonder why any video can be a root node. So the answer is, in the spanning tree all
the nodes of a graph are included and because it is connected then there must be at least one edge, which will join it
to the rest of the tree.

Step 3 - Check outgoing edges and select the one with less cost

After choosing the root node S, we see that S,A and S,C are two edges with weight 7 and 8, respectively. We choose
the edge S,A as it is lesser than the other.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Now, the tree S-7-A is treated as one node and we check for all edges going out from it. We select the one which has
the lowest cost and include it in the tree.

After this step, S-7-A-3-C tree is formed. Now we'll again treat it as a node and will check all the edges again.
However, we will choose only the least cost edge. In this case, C-3-D is the new edge, which is less than other edges'
cost 8, 6, 4, etc.

After adding node D to the spanning tree, we now have two edges going out of it having the same cost, i.e. D-2-T and
D-2-B. Thus, we can add either one. But the next step will again yield edge 2 as the least cost. Hence, we are
showing a spanning tree with both edges included.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

We may find that the output spanning tree of the same graph using two different algorithms is same.

Q. 5 Explain Dijkstra’s algorithm to find the shortest path by taking an example.

Shortest Path using Dijkstra’s Algorithm

The idea of the algorithm is very simple.

1. It maintains a list of unvisited vertices.


2. It chooses a vertex (the source) and assigns a maximum possible cost (i.e. infinity) to every other vertex.
3. The cost of the source remains zero as it actually takes nothing to reach from the source vertex to itself.
4. In every subsequent step of the algorithm it tries to improve(minimize) the cost for each vertex. Here the cost can be
distance, money or time taken to reach that vertex from the source vertex. The minimization of cost is a multi-step
process.
1. For each unvisited neighbor (vertex 2, vertex 3, vertex 4) of the current vertex (vertex 1) calculate the new
cost from the vertex (vertex 1).
2. For e.g. the new cost of vertex 2 is calculated as the minimum of the two ( (existing cost of vertex 2) or (sum of
cost of vertex 1 + the cost of edge from vertex 1 to vertex 2) )
5. When all the neighbors of the current node are considered, it marks the current node as visited and is removed from
the unvisited list.
6. Select a vertex from the list of unvisited nodes (which has the smallest cost) and repeat step 4.
7. At the end there will be no possibilities to improve it further and then the algorithm ends

For demonstration we will consider the below graph:


ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Step Wise Execution

Step 1:

Mark Vertex 1 as the source vertex. Assign a cost zero to Vertex 1 and (infinite to all other vertices). The state is as
follows:

Step 2:

For each of the unvisited neighbors (Vertex 2, Vertex 3 and Vertex 4) calculate the minimum cost as min(current cost
of vertex under consideration, sum of cost of vertex 1 and connecting edge). Mark Vertex 1 as visited , in the diagram
we border it black. The new state would be as follows:
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Step 3:

Choose the unvisited vertex with minimum cost (vertex 4) and consider all its unvisited neighbors (Vertex 5 and
Vertex 6) and calculate the minimum cost for both of them. The state is as follows:

Step 4:

Choose the unvisited vertex with minimum cost (vertex 2 or vertex 5, here we choose vertex 2) and consider all its
unvisited neighbors (Vertex 3 and Vertex 5) and calculate the minimum cost for both of them. Now, the current cost
of Vertex 3 is [4] and the sum of (cost of Vertex 2 + cost of edge (2,3) ) is 3 + 4 = [7]. Minimum of 4, 7 is 4. Hence
the cost of vertex 3 won’t change. By the same argument the cost of vertex 5 will not change. We just mark the
vertex 2 as visited, all the costs remain same. The state is as follows:
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Step 5:

Choose the unvisited vertex with minimum cost (vertex 5) and consider all its unvisited neighbors (Vertex 3 and
Vertex 6) and calculate the minimum cost for both of them. Now, the current cost of Vertex 3 is [4] and the sum of
(cost of Vertex 5 + cost of edge (5,3) ) is 3 + 6 = [9]. Minimum of 4, 9 is 4. Hence the cost of vertex 3 won’t change.
Now, the current cost of Vertex 6 is [6] and the sum of (cost of Vertex 5 + cost of edge (3,6) ) is 3 + 2 = [5].
Minimum of 6, 5 is 45. Hence the cost of vertex 6 changes to 5. The state is as follows:

Step 6:

Choose the unvisited vertex with minimum cost (vertex 3) and consider all its unvisited neighbors (none). So mark it
visited. The state is as follows:
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

Step 7:

Choose the unvisited vertex with minimum cost (vertex 6) and consider all its unvisited neighbors (none). So mark it
visited. The state is as follows:

Now there is no unvisited vertex left and the execution ends. At the end we know the shortest paths for all the
vertices from the source vertex 1. Even if we know the shortest path length, we do not know the exact list of vertices
which contributes to the shortest path until we maintain them separately or the data structure supports it.

Q. 6 Explain Hashing in detail.

Hashing

There are many possibilities for representing the dictionary and one of the best methods for representing is hashing.
Hashing is a type of a solution which can be used in almost all situations. Hashing is a technique which uses less key
comparisons and searches the element in O(n) time in the worst case and in an average case it will be done in O(1)
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

time. This method generally used the hash functions to map the keys into a table, which is called a hash table.

1) Hash table

Hash table is a type of data structure which is used for storing and accessing data very quickly. Insertion of data in a
table is based on a key value. Hence every entry in the hash table is defined with some key. By using this key data
can be searched in the hash table by few key comparisons and then searching time is dependent upon the size of the
hash table.

2) Hash function

Hash function is a function which is applied on a key by which it produces an integer, which can be used as an
address of hash table. Hence one can use the same hash function for accessing the data from the hash table. In this the
integer returned by the hash function is called hash key.

Types of hash function

There are various types of hash function which are used to place the data in a hash table,

1. Division method

In this the hash function is dependent upon the remainder of a division. For example:-if the record 52,68,99,84 is to
be placed in a hash table and let us take the table size is 10.

Then:

h(key)=record% table size.


2=52%10
8=68%10
9=99%10
4=84%10

2. Mid square method

In this method firstly key is squared and then mid part of the result is taken as the index. For example: consider that if
we want to place a record of 3101 and the size of table is 1000. So 3101*3101=9616201 i.e. h (3101) = 162 (middle
3 digit)

3. Digit folding method

In this method the key is divided into separate parts and by using some simple operations these parts are combined to
produce a hash key. For example: consider a record of 12465512 then it will be divided into parts i.e. 124, 655, 12.
After dividing the parts combine these parts by adding it.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms
H(key)=124+655+12
=791

Characteristics of good hashing function

1. The hash function should generate different hash values for the similar string.
2. The hash function is easy to understand and simple to compute.
3. The hash function should produce the keys which will get distributed, uniformly over an array.
4. A number of collisions should be less while placing the data in the hash table.
5. The hash function is a perfect hash function when it uses all the input data.

Collision

It is a situation in which the hash function returns the same hash key for more than one record, it is called as
collision. Sometimes when we are going to resolve the collision it may lead to a overflow condition and this overflow
and collision condition makes the poor hash function.

Collision resolution technique

If there is a problem of collision occurs then it can be handled by apply some technique. These techniques are called
as collision resolution techniques. There are generally four techniques which are described below.

1) Chaining

It is a method in which additional field with data i.e. chain is introduced. A chain is maintained at the home bucket.
In this when a collision occurs then a linked list is maintained for colliding data.

Example: Let us consider a hash table of size 10 and we apply a hash function of H(key)=key % size of table. Let us
take the keys to be inserted are 31,33,77,61. In the above diagram we can see at same bucket 1 there are two records
which are maintained by linked list or we can say by chaining method.

2) Linear probing

It is very easy and simple method to resolve or to handle the collision. In this collision can be solved by placing the
second record linearly down, whenever the empty place is found. In this method there is a problem of clustering
which means at some place block of a data is formed in a hash table.

Example: Let us consider a hash table of size 10 and hash function is defined as H(key)=key % table size. Consider
that following keys are to be inserted that are 56,64,36,71.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

In this diagram we can see that 56 and 36 need to be placed at same bucket but by linear probing technique the
records linearly placed downward if place is empty i.e. it can be seen 36 is placed at index 7.

3) Quadratic probing

This is a method in which solving of clustering problem is done. In this method the hash function is defined by the
H(key)=(H(key)+x*x)%table size. Let us consider we have to insert following elements that are:-67, 90,55,17,49.

In this we can see if we insert 67, 90, and 55 it can be inserted easily but at case of 17 hash function is used in such a
manner that :-(17+0*0)%10=17 (when x=0 it provide the index value 7 only) by making the increment in value of x.
let x =1 so (17+1*1)%10=8.in this case bucket 8 is empty hence we will place 17 at index 8.

4) Double hashing

It is a technique in which two hash function are used when there is an occurrence of collision. In this method 1 hash
function is simple as same as division method. But for the second hash function there are two important rules which
are

1. It must never evaluate to zero.


2. Must sure about the buckets, that they are probed.

The hash functions for this technique are:

H1(key)=key % table size


H2(key)=P-(key mod P)

Where, p is a prime number which should be taken smaller than the size of a hash table.

Example: Let us consider we have to insert 67, 90,55,17,49.

In this we can see 67, 90 and 55 can be inserted in a hash table by using first hash function but in case of 17 again the
bucket is full and in this case we have to use the second hash function which is H2(key)=P-(key mode P) here p is a
prime number which should be taken smaller than the hash table so value of p will be the 7.

i.e. H2(17)=7-(17%7)=7-3=4 that means we have to take 4 jumps for placing the 17. Therefore 17 will be placed at
index 1.
ARYA COLLEGE OF ENGINEERING & RESEARCH CENTRE
JAIPUR
GUESS PAPERS
(II B. Tech. III Semester 2019- 2020)
3CS4-05 : Data Structure & Algorithms

You might also like