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

(Uscs33) - (Data Structures) : Question & Answers Type: 100% Theory

This document contains questions and answers related to data structures. It discusses various data structure concepts in detail including: 1. It defines data structures as specialized formats for organizing and storing data and provides examples like arrays, files, records, tables, trees. 2. It explains different types of data structures like lists, ordered lists, composite data types, primitive data types, arrays and their operations. 3. It discusses array implementation of lists, their advantages, and operations like traversing, searching, insertion, deletion, sorting, merging that can be performed on arrays.

Uploaded by

Sasi S INDIA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
482 views

(Uscs33) - (Data Structures) : Question & Answers Type: 100% Theory

This document contains questions and answers related to data structures. It discusses various data structure concepts in detail including: 1. It defines data structures as specialized formats for organizing and storing data and provides examples like arrays, files, records, tables, trees. 2. It explains different types of data structures like lists, ordered lists, composite data types, primitive data types, arrays and their operations. 3. It discusses array implementation of lists, their advantages, and operations like traversing, searching, insertion, deletion, sorting, merging that can be performed on arrays.

Uploaded by

Sasi S INDIA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

(USCS33) - (DATA STRUCTURES)


Unit-1
Question & Answers
Type: 100% Theory

PART – A ANSWERS (2 MARKS)

1. Define of a Data Structures? [Nov/Dec 2015, Nov 2014]


A data structure is a specialized format for organizing and storing data. General data
structure types include the array, the file, the record, the table, the tree, and so on.

2. Give few examples for data structures? [Nov/Dec 2015, Apl/May 2014]
A hash table is a common implementation of an associative array. A record (also called
tuple or struct) is an aggregate data structure. A record is a value that contains other values,
typically in fixed number and sequence and typically indexed by names. The elements of
records are usually called fields or members.

3. What is a list? [Apl/May 2015]


The name list is also used for several concrete data structures that can be used to
implement abstract lists, especially linked lists. Many programming languages provide support
for list data types, and have special syntax and semantics for listsand list operations.

4. Define Ordered Lists?


The structure of an ordered list is a collection of items where each item holds a
relative position that is based upon some underlying characteristic of the item.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 1 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

5. What are the advantages in the array implementation of Lists? [Nov 2014]
 Easy to implement
 Random access is easier
 suitable when the number of elements are predefined or already known.

6. What is composite data type? [Apl/May 2014]


Using composite data, we can manage multiple pieces of related data as a single datum.
For example if you wanted to store information about a person you could store there date of
birth, sex, address etc.

7. What is primitive data type?


Primitive data types are the basic units of a langauge; each primitive value is a single
datum and holds that datum directly.

8. Define Array?

An array is an aggregate data structure that is designed to store a group of objects of


the same or different types. Arrays can hold primitives as well as references. The array is the
most efficient data structure for storing and accessing a sequence of objects.

9. List out the Array Operations?


a. Traversing
b. Searching
c. Insertion
d. Deletion
e. Sorting
f. Merging

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 2 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

10. What is a Data types? [Apl/May 2015]


A data type in a programming language is a set of data with values having predefined
characteristics. Examples of data types are: integer, floating point unit number, character,
string, and pointer. Usually, a limited number of such data types come built into a language.

PART – B ANSWERS (5 MARKS)

1. What are composite data types? Explain. [Nov/Dec 2015]


Composite data types:
They are the data types which are derived from the primitive data type.
They are slightly complex then the primitive.
They can be homogeneous and heterogeneous.
Composite data type are broadly classified into two major categories:
 Linear Data Type
 Non Linear Data Type
Linear Data Type:
Linear data types are those data types whose are homogeneous.
example:
a) Arrays
b) Linked List
c) Stacks
d) Queues
Non Linear Data Type:
These are those data types whose elements are heterogeneous.
example:
a) Trees
b) Graphs

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 3 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

2. What are the various operations of Array? Explain. [Nov/Dec 2015]


Following operations can be performed on arrays:
1. Traversing: It is used to access each data item exactly once so that it can be processed.
2. Searching: It is used to find out the location of the data item if it exists in the given
collection of data items.
3. Insertion: It is used to add a new data item in the given collection of data items.
4. Deletion: It is used to delete an existing data item from the given collection of data
items.
5. Sorting: It is used to arrange the data items in some order i.e. in ascending or
descending order in case of numerical data and in dictionary order in case of
alphanumeric data.
6. Merging: It is used to combine the data items of two sorted files into single file in the
sorted form

3. Explain Primitive and Composite data types. [Apl/May 2015]


There are two types of data types in data structure:
 Primitive Data Types
 Composite Data Types
Primitive data types: Primitive data types are the predefine data types like int, char, float etc
in 'C' language. They are the simplest data types.

Composite data types:


They are the data types which are derived from the primitive data type.
They are slightly complex then the primitive.
They can be homogeneous and heterogeneous.
Composite data type are broadly classified into two major categories:
 Linear Data Type
 Non Linear Data Type

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 4 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Linear Data Type:


Linear data types are those data types whose are homogeneous.
example:
e) Arrays
f) Linked List
g) Stacks
h) Queues
Non Linear Data Type:
These are those data types whose elements are heterogeneous.
example:
c) Trees
d) Graphs

4. What is a data Structure? Why is it Important? [Apl/May 2015]

Data structure is a particular way of storing and organizing information in


a computer so that it can be retrieved and used most productively.

Different kinds of data structures are meant for different kinds of


applications, and some are highly specialized to specific tasks.

Data structures are important for the following reasons:

1. Data structures are used in almost every program or software system.

2. Specific data structures are essential ingredients of many efficient algorithms, and
make possible the management of huge amounts of data, such as large integrated
collection of databases.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 5 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

3. Some programming languages emphasize data structures, rather than algorithms,


as the key organizing factor in software design.

5. What is List? Explain. [Nov 2014]


The name list is also used for several concrete data structures that can be used to
implement abstract lists, especially linked lists. Many programming languages provide support
for list data types, and have special syntax and semantics for listsand list operations.
Operations

Implementation of the list data structure may provide some of the following operations:

 a constructor for creating an empty list;


 an operation for testing whether or not a list is empty;
 an operation for prepending an entity to a list
 an operation for appending an entity to a list
 an operation for determining the first component (or the "head") of a list
 an operation for referring to the list consisting of all the components of a list except for its
first (this is called the "tail" of the list.)
Implementations
Lists are typically implemented either as linked lists (either singly or doubly linked) or
as arrays, usually variable length or dynamic arrays.

6. What is an array? Explain. Apl/May 2014 [ Nov 2014]


Array is a container which can hold fix number of items and these items should be of same
type. Most of the data structure make use of array to implement their algorithms.

Following are important terms to understand the concepts of Array.

Element − Each item stored in an array is called an element.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 6 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Index − Each location of an element in an array has a numerical index which is used
to identify the element.

ARRAY REPRESENTATION
Arrays can be declared in various ways in different languages. For illustration, let's
take C array declaration.

Arrays can be declared in various ways in different languages. For illustration, let's
take C array declaration.

As per above shown illustration, following are the important points to be considered.

 Index starts with 0.

 Array length is 8 which means it can store 8 elements.

 Each element can be accessed via its index. For example, we can fetch element at
index 6 as 9.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 7 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

PART – C ANSWERS (10 MARKS)

1. How to choose a data structure? Explain. [Nov 2014]


Data Structure is a way of collecting and organising data in such a way that we can
perform operations on these data in an effective way.

Data Structures is about rendering data elements in terms of some relationship, for
better organization and storage.

For example, we have data player's name "Virat" and age 26. Here "Virat" is
of String data type and 26 is of integer data type.

We can organize this data as a record like Player record. Now we can collect and store
player's records in a file or database as a data structure. For example: "Dhoni" 30, "Gambhir"
31, "Sehwag" 33

In simple language, Data Structures are structures programmed to store ordered data,
so that various operations can be performed on it easily.

Basic types of Data Structures


As we discussed above, anything that can store data can be called as a data strucure,
hence Integer, Float, Boolean, Char etc, all are data structures. They are known as Primitive
Data Structures.

Then we also have some complex Data Structures, which are used to store large and
connected data. Some example of Abstract Data Structure are :

 Linked List
 Tree
 Graph
 Stack, Queue etc.

All these data structures allow us to perform different operations on data.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 8 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

We select these data structures based on which type of operation is required. We will
look into these data structures in more details in our later lessons.

2. Write a detailed note on array and its operations. [Apl/May 2015]


Array is a container which can hold fix number of items and these items should be of same
type. Most of the data structure make use of array to implement their algorithms. Following are
important terms to understand the concepts of Array.

 Element − Each item stored in an array is called an element.

 Index − Each location of an element in an array has a numerical index which is used to
identify the element.

Basic Operations
Following are the basic operations supported by an array.

 Traverse − print all the array elements one by one.

 Insertion − add an element at given index.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 9 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 Deletion − delete an element at given index.

 Search − search an element using given index or by value.

 Update − update an element at given index.

In C, when an array is initialized with size, then it assigns defaults values to its
elements in following order.

Insertion Operation
Insert operation is to insert one or more data elements into an array. Based on the
requirement, new element can be added at the beginning, end or any given index of array.

Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.

Search Operation
You can perform a search for array element based on its value or its index.

Update Operation
Update operation refers to updating an existing element from the array at a given
index.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 10 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

3. Discuss about the list implementation concepts. [Nov/Dec 2015]


Linked List is a linear data structure and it is very common data structure which consists of
group of nodes in a sequence which is divided in two parts.

Each node consists of its own data and the address of the next node and forms a chain.
Linked Lists are used to create trees and graphs.

Advantages of Linked Lists

 They are a dynamic in nature which allocates the memory when required.
 Insertion and deletion operations can be easily implemented.
 Stacks and queues can be easily executed.
 Linked List reduces the access time.

Disadvantages of Linked Lists

 The memory is wasted as pointers require extra memory for storage.


 No element can be accessed randomly; it has to access each node sequentially.
 Reverse Traversing is difficult in linked list.

Applications of Linked Lists

 Linked lists are used to implement stacks, queues, graphs, etc.


 Linked lists let you insert elements at the beginning and end of the list.
 In Linked Lists we don’t need to know the size in advance.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 11 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Types of Linked Lists

Singly Linked List : Singly linked lists contain nodes which have a data part as well
as an address part i.e. next, which points to the next node in sequence of nodes. The operations
we can perform on singly linked lists are insertion, deletion and traversal.

Doubly Linked List : In a doubly linked list, each node contains two links the first link
points to the previous node and the next link points to the next node in the sequence.

Circular Linked List : In the circular linked list the last node of the list contains the
address of the first node and forms a circular chain.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 12 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

4. Write a detailed note on primitive and composite Data types.

There are 2 categories of data type in ActionScript:

 Primitive Data Types.


 Composite Data Types.

Primitive Data Types

Primitive data types are the basic units of a langauge; each primitive value is a single
datum and holds that datum directly.

We have seen examples of numbers and strings these are a the most basic primitive
data types.

They are simple and can hold text messages, frame numbers, counters, etc..

The primitive data types that Action Script supports are:

 number.
 string.
 boolean.
 undefined.
 null.

Composite Data Types

Using composite data, we can manage multiple pieces of related data as a single datum.
As single variables but then when you wanted to add another person you would have to
remember to create all the variables but with slightly different names.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 13 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

AS the number of people increased so would the complexity of your naming and the
relationship between the variables would be lost.

In Action Script you could create an object called person which had properties to store
the date of birth, sex, address etc, you would then create instances of that object.

The composite data types that Action Script supports are:

 array.
 object.
 movie clip.
 functions.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-1 QA

Unit – 1 Question & Answer Page 14 of 14


ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

(USCS33) - (DATA STRUCTURES)


Unit-2
Question & Answers
Type: 100% Theory

PART – A ANSWERS (2 MARKS)

1. What is an Expression? [Apl/May 2014]


The way to write arithmetic expression is known as notation. An arithmetic expression can
be written in three different but equivalent notations, i.e., without changing the essence or
output of expression. These notations are

 Infix Notation

 Prefix (Polish) Notation

 Postfix (Reverse-Polish) Notation

These notations are named as how they use operator in expression.

2. List any two Applications of Stack [Apl/May 2014]

 Parsing
 Recursive Function

3. State the advantages of using postfix notation? [Nov 2014]


a. You don’t need rules of precedence
b. You don’t need rules for right and left associativity
c. You don’t need parentheses to override the above rules

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 1 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

4. State the different ways of representing expressions. [Nov 2014]


a) push() − pushing (storing) an element on the stack.

b) pop() − removing (accessing) an element from the stack.

5. Define an overflow condition. [Apl/May 2015]


Stack overflow happens when we try to push one more item onto our stack than it can
actually hold. You see, the stack usually can only hold so much stuff.
6. Define an underflow condition.
Stack underflow happens when we try to pop (remove) an item from the stack, when
nothing is actually there to remove.
7. Define postfix. [Nov/Dec 2015]
Operator is postfixed to the operands i.e., operator is written after the operands.
For example ab+. This is equivalent to its infix notation a+b.
8. Define Stack
A stack is a data structure used to store a collection of objects. Individual items can be
added and stored in a stack using a push operation. Objects can be retrieved using
a pop operation, which removes an item from the stack.
9. Write note on Infix Expression.
Operator is prefixed to operands, i.e. operator is written ahead of operands.
For example +ab. This is equivalent to its infix notation a+b.
10. State the advantages of using Infix notation? [Nov/Dec 2015]
a. You grew up with it
b. It’s easier to see visually what is done first

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 2 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

PART – B ANSWERS (5 MARKS)

1. Discus overflow and underflow operations. [Apl/May 2014]

Now that we have a basic picture in mind of what a stack conceptually looks like, we
can define what underflow and overflow are.

Stack underflow happens when we try to pop (remove) an item from the stack, when
nothing is actually there to remove.

This will raise an alarm of sorts in the computer, because we told it to do something
that cannot be done.

Stack overflow happens when we try to push one more item onto our stack than it can
actually hold. You see, the stack usually can only hold so much stuff.

Typically, we allocate (set aside) where the stack is going to be in memory and how
big it can get.

So, when we stick too much stuff there or try to remove nothing, we will generate a
stack overflow condition or stack underflow condition, respectively.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 3 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

2. How to convert from infix to postfix. [Nov 2014]

a) Create an empty stack called opstack for keeping operators. Create an empty list for
output.
b) Convert the input infix string to a list by using the string method split.
c) Scan the token list from left to right.
a. If the token is an operand, append it to the end of the output list.
b. If the token is a left parenthesis, push it on the opstack.
c. If the token is a right parenthesis, pop the opstack until the corresponding left
parenthesis is removed. Append each operator to the end of the output list.
d. If the token is an operator, *, /, +, or -, push it on the opstack. However, first
remove any operators already on the opstack that have higher or equal
precedence and append them to the output list.
d) When the input expression has been completely processed, check the opstack. Any
operators still on the stack can be removed and appended to the end of the output list.

Converting A * B + C * D to Postfix Notation

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 4 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

3. How to Evaluate postfix? [Nov 2014 &Nov/Dec 2015]

a) Create an empty stack called operand Stack.


b) Convert the string to a list by using the string method split.
c) Scan the token list from left to right.
a. If the token is an operand, convert it from a string to an integer and push the
value onto the operand Stack.
b. If the token is an operator, *, /, +, or -, it will need two operands. Pop
the operand Stack twice. The first pop is the second operand and the second pop
is the first operand. Perform the arithmetic operation. Push the result back on
the operand Stack.
d) When the input expression has been completely processed, the result is on the stack.
Pop the operand Stack and return the value.

4. List the application of Stack? [Apl/May 2015]

 Parsing
 Recursive Function
 Calling Function
 Expression Evaluation
 Expression Conversion

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 5 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

o Infix to Postfix
o Infix to Prefix
o Postfix to Infix
o Prefix to Infix
 Towers of hanoi

Expression Representation

Infix Prefix Postfix

a+b +ab ab+

a+b*c +a*bc abc*+

(a + b) * (c - d) *+ab-cd ab+cd-*

5. Write detail Stack Operations.


Stack operations may involve initializing the stack, using it and then de-initializing it.
Apart from these basic stuffs, a stack is used for the following two primary operations −

 push() − pushing (storing) an element on the stack.

 pop() − removing (accessing) an element from the stack.

When data is PUSHed onto stack.

To use a stack efficiently we need to check status of stack as well. For the same purpose,
the following functionality is added to stacks −

 peek() − get the top data element of the stack, without removing it.

 isFull() − check if stack is full.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 6 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 isEmpty() − check if stack is empty.

At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer
always represents the top of the stack, hence named top. The toppointer provides top value of
the stack without actually removing it.

6. Convert Infix to Postfix.


A * B ^ C + D becomes A B C ^ * D +
S.No current symbol operator stack postfix string
1 A A
2 * * A
3 B * AB
4 ^ *^ AB
5 C *^ ABC
6 + + ABC^*
7 D + ABC^*D
8 ABC^*D+

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 7 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

PART – C ANSWERS (10 MARKS)

1. Write detail about Stack?


A stack is a data structure used to store a collection of objects. Individual items can be
added and stored in a stack using a push operation. Objects can be retrieved using
a pop operation, which removes an item from the stack.

Basic features of Stack


A. Stack is an ordered list of similar data type.
B. Stack is a LIFO structure. (Last in First out).
C. push() function is used to insert new elements into the Stack and pop() is used to delete
an element from the stack. Both insertion and deletion are allowed at only one end of
Stack called Top.
D. Stack is said to be in Overflow state when it is completely full and is said to be
in Underflow state if it is completely empty.
Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to
stack - letter by letter - and then pop letters from the stack.
There are other uses also like : Parsing, Expression Conversion(Infix to Postfix, Postfix
to Prefix etc) and many more.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 8 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Implementation of Stack
Stack can be easily implemented using an Array or a Linked List. Arrays are quick, but
are limited in size and Linked List requires overhead to allocate, link, unlink, and
deallocate, but is not limited in size. Here we will implement Stack using array.

Operations
Stack operations may involve initializing the stack, using it and then de-initializing it.
Apart from these basic stuffs, a stack is used for the following two primary operations −

 push() − pushing (storing) an element on the stack.

 pop() − removing (accessing) an element from the stack.

When data is PUSHed onto stack.

To use a stack efficiently we need to check status of stack as well. For the same purpose,
the following functionality is added to stacks −

 peek() − get the top data element of the stack, without removing it.

 isFull() − check if stack is full.

 isEmpty() − check if stack is empty.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 9 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

2. Convert infix to Postfix.


A * (B + C * D) + E becomes A B C D * + * E +
Sl. No current symbol operator stack postfix string
1 A A
2 * * A
3 ( *( A
4 B *( AB
5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
9 ) * ABCD*+
10 + + ABCD*+*
11 E + ABCD*+*E
12 ABCD*+*E+

A summary of the rules follows:

1. Print operands as they arrive.

2. If the stack is empty or contains a left parenthesis on top, push the incoming
operator onto the stack.

3. If the incoming symbol is a left parenthesis, push it on the stack.

4. If the incoming symbol is a right parenthesis, pop the stack and print the
operators until you see a left parenthesis. Discard the pair of parentheses.

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 10 of 11
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

5. If the incoming symbol has higher precedence than the top of the stack, push it on
the stack.

6. If the incoming symbol has equal precedence with the top of the stack, use
association. If the association is left to right, pop and print the top of the stack and
then push the incoming operator. If the association is right to left, push the incoming
operator.

7. If the incoming symbol has lower precedence than the symbol on the top of the
stack, pop the stack and print the top operator. Then test the incoming operator
against the new top of stack.

8. At the end of the expression, pop and print all operators on the stack. (No
parentheses should remain.)

RAAK/B.SC.(CS) /C. VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURE/UNIT-2 QA
Unit – 2 Question & Answer Page 11 of 11
ACADEMIC YEAR 2015-2018 REGULATION 2012

USCS 33 – DATA STRUCTURE


Unit III
Type: 100% Theory

Questions & Answers


1. What is a queue?(Apr/May/Nov 2014)
Queue is an abstract data type or a linear data structure, in which the first
element is inserted from one end called REAR(also called tail), and the deletion of
existing element takes place from the other end called as FRONT(also called head). This
makes queue as FIFO data structure, which means that element inserted first will also be
removed first.

2. Mention the basic features of Queue.


 Like Stack, Queue is also an ordered list of elements of similar data types.
 Queue is a FIFO( First in First Out ) structure.
 Once a new element is inserted into the Queue, all the elements inserted before the new
element in the queue must be removed, to remove the new element.
 peek( ) function is often used to return the value of first element without dequeuing it.

3. Define Linked list.(Apr/May 2012)

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 1 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

 Linked list is a collection of data in which each element contains the location of the next
element—that is, each element contains two parts: data and link.
 The name of the list is the same as the name of this pointer variable.

4. Define Doubly Linked List.(Apr/May/Nov 2015 Apl/May 2016)


In Doubly Linked List, each node contains two address fields. One address field
for storing address of next node to be followed and second address field contain
address of previous node linked to it.

5. How do you represent a polynomial?(Nov/Dec 2011, Nov 2012)


 Polynomial is an expression that contains more than two terms. A term is made up of
coefficient and exponent. An example of polynomial is
o P(x) = 4x3+6x2+7x+9
 A polynomial thus may be represented using arrays or linked lists.
 Array representation assumes that the exponents of the given expression are arranged
from 0 to the highest value (degree), which is represented by the subscript of the array
beginning with 0.
 The coefficients of the respective exponent are placed at an appropriate index in the
array.

6. Define Singly Linked List.(Nov 2012)


In Linked List two successive nodes are linked together in linear fashion. Each
Node contains address of the next node to be followed. In Singly Linked List only Linear

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 2 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

or Forward Sequential movement is possible. Elements are accessed sequentially, no


direct access is allowed.

7. List out the operations of linked list.


1. Creation
2. Insertion
3. Deletion
4. Traversing
5. Searching
6. Concatenation
7. Display
 The creation operation is used to create a linked list.
 Insertion operation is used to insert a new node in the linked list at the specified
position. A new node may be inserted at the beginning of a linked list , at the end of
the linked list , at the specified position in a linked list. If the list itself is empty , then
the new node is inserted as a first node.
 Deletion operation is used to delete on item from the linked list. It may be deleted
from the beginning of a linked list , specified position in the list.
 Traversing operation is a process of going through all the nodes of a linked list from
one end to the another end. If we start traversing from the very first node towards the
last node , It is called forward traversing.
 Traversal start from the last node towards the first node , it is called back word
traversing
 Searching operation is a process of accessing the desired node in the list. We start
searching node –by-node and compare the data of the node with the key.
 Concatenation operation is the process of appending the second list to the end of the
first list. When we concatenate two lists , the resultant list becomes larger in size.
 Display operation is used to print each and every node’s information.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 3 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

8. What are Circularly linked list?


In Circular Linked List, Address field of Last node contain address of “First
Node”. Linked List is made circular by linking first and last node , so it looks like
circular chain.

9. Mention the different types of linked list.


 Single linked list
 Double linked list
 Circular linked list
 Circular double linked list

10. List the applications of linked list.


 Linked lists are used in many other data structures.
 Linked lists are used in polynomial manipulation
 Linked lists can be used to implement stacks, queues, graphs, etc.

11. What are the operations on Queues.


Insert Operation: Enqueue function inserts the given element in the given queue.
Delete Operation: Dequeue function deletes (head) the element in the given queue

12. Define list.


 The list is a sequential data structure.
 Lists are a way to store many different values under a single variable.
 Every item in this list is numbered with an index.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 4 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

Part- B

1. How to insert and delete node in linked list?


To insert and delete node in linked list four cases can arise:
 Inserting into an empty list.
 Insertion at the beginning of the list.
 Insertion at the end of the list.
 Insertion in the middle of the list.

Inserting a node at the end of the linked list

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 5 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

Inserting a node in the middle of the linked list

DELETING A NODE
 Before deleting a node in a linked list, we apply the search algorithm.
 If the flag returned from the search algorithm is true (the node is found), we can
delete the node from the linked list.
However, deletion is simpler than insertion: we have only two cases—
1. Deleting the first node and deleting any other node.
2. Deletion of the last and the middle nodes can be done by the same process.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 6 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

Deleting the first node of a linked list

Deleting a node at the middle or end of a linked list

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 7 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

2. Describe the implementation of Queue?


 Queue can be implemented using an Array, Stack or Linked List.
 The easiest way of implementing a queue is by using an Array.
 Initially the head(FRONT) and the tail(REAR) of the queue points at the first index of
the array (starting the index of array from 0).
 As we add elements to the queue, the tail keeps on moving ahead, always pointing to
the position where the next element will be inserted, while the head remains at the first
index.
 When we remove element from Queue, we can follow two possible approaches.
 In first approach, we remove the element at head position, and then one by one move all
the other elements on position forward. In second approach we remove the element from
head position and then move head to the next position.
 In first approach there is an overhead of shifting the elements one position forward every
time we remove the first element.
 In second approach , there is no such overhead, but whenever we move head one
position ahead, after removal of first element, the size on Queue is reduced by one space
each time.

3. Explain the various operations of queue.( Nov 2014)

A queue is an ordered collection of items where the addition of new items happens
at one end, called the “rear,” and the removal of existing items occurs at the other end,
commonly called the “front.”
Types of Operation in queue:
 Queue() creates a new queue that is empty. It needs no parameters and returns an empty
queue.
 Enqueue(item) adds a new item to the rear of the queue. It needs the item and returns
nothing.
 Dequeue() removes the front item from the queue. It needs no parameters and returns the
item. The queue is modified.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 8 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

 IsEmpty() tests to see whether the queue is empty. It needs no parameters and returns a
boolean value.
 Size() returns the number of items in the queue. It needs no parameters and returns an
integer.

4. Discuss the types of Linked List.(Apr may 2014)


 Linked list: A linked list is a self referential structure which contain a member field
that point to the same structure type
 Linear Singly linked list: A list type in which each node points to the next node and
the last node points to NULL.
 Circular linked list: Lists which have no beginning and no end. The last node points
back to the first item.
 Doubly linked list or Two-way linked list: These lists contain double set of pointers,
one pointing to the next item and other pointing to the preceding item. So one can
traverse the list in either direction.
 Circularly doubly linked list: It employs both the forward and backward pointer in
circular form.

5. Write the advantages of linked list.(Apr/May 2014)

 Linked List is Dynamic data Structure .


 Linked List can grow and shrink during run time.
 Insertion and Deletion Operations are Easier
 Efficient Memory Utilization ,i.e no need to pre-allocate memory
 Faster Access time,can be expanded in constant time without memory overhead
 Linear Data Structures such as Stack,Queue can be easily implemeted using Linked
list

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 9 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

6. How to represent polynomial addition in data structure.(Apr 2011& NOV 2015)

What is a polynomial?

A polynomial object is a homogeneous ordered list of pairs <exponent, coefficient>,


where each coefficient is unique. Operations include returning the degree, extracting the
coefficient for a given exponent, addition, multiplication, evaluation for a given input.

Representation of Polynomial 1 - Fixed maximal degree

Representation of polynomial 2 - Wastes space if maximal polynomial degree is less

than maximal possible degree.

- Dynamic degree

Representation of polynomial 3 - Wastes space if polynomial is sparse.

- Sparse polynomials, global storage

Representation of polynomial 4 - Limited number of total polynomial terms.

- Sparse polynomials, local storage

PART – C

1. Explain the operations of Singly Linked List.(Apr 2012)

Singly Linked list with below operations

1) CREATION
2) INSERT AT STARTING
3) INSERT AT MIDDLE(USER'S CHOICE)
4) INSERT AT END
5) DELETE 1ST NODE
6) DELETE LAST NODE
7) DELETE MIDDLE NODE(USER'S CHOICE)
8) DISPLAY
RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 10 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

2. Explain the operations of Doubly Linked List?(Nov 2012 & 2014)

Definition:

A doubly linked list is a linked data structure that consists of a set of sequentially
linked records called nodes. Each node contains two fields, called links, that are references
to the previous and to the next node in the sequence of nodes. The beginning and ending
nodes’ previous and next links.

Various operations which can be performed over doubly linked list:

 Add a node in a list at beginning or at end or in between.


 Delete a node from list at specific location.
 Reverse a list.
 Count nodes present in the list.
 Print the list to see all the nodes present in the list.

Add a node in a list.

Insertion of a node in a linked list can be done at three places, viz. at start, in
between at a specified location or at end.

Inserting a node at the start of list :


Algorithm :
 Update the next pointer of the new node to the head node and make prev pointer of the
new node as NULL
 Now update head node’s prev pointer to point to new node and make new node as head
node.

Inserting a node at the end of the list :


Algorithm :

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 11 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

 Traverse the list to end. Let’s call the current last node of list as Last node.
 Make next pointer of New node to point to NULL and prev pointer of new node to point
to Last node.
 Update next pointer of Last node to point to new Node.

Delete a node from a list.


As similar to Insertion of a node in a linked list, deletion can also be done at three
places, viz. from start, in between at a specified location or from end.

Reversing a list.
This is one of the favorite question which interviewer is bound to ask while
interviewing a candidate on data structures.

Counting nodes in list/ Printing content of list.


This one is the easiest operation on Doubly Linked List. All what you have to do
is to traverse the list and while traversing you need to keep on increment counter (while
counting nodes in list)/ you need to print the data of each node (while printing the nodes).

3. Explain polynomial addition in singly linked list(Apl/May 2015)


 Polynomial Manipulation
 Representation
 Addition
 Multiplication

Representation of a Polynomial: A polynomial is an expression that contains more than


two terms. A term is made up of coefficient and exponent. An example of polynomial is

P(x) = 4x3+6x2+7x+9

A polynomial thus may be represented using arrays or linked lists. Array


representation assumes that the exponents of the given expression are arranged from 0 to
the highest value (degree), which is represented by the subscript of the array beginning

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 12 of 13
ACADEMIC YEAR 2015-2018 REGULATION 2012

with 0. The coefficients of the respective exponent are placed at an appropriate index in
the array. The array representation for the above polynomial expression is given below:

A polynomial may also be represented using a linked list. A structure may be


defined such that it contains two parts- one is the coefficient and second is the
corresponding exponent. The structure definition may be given as shown below:

struct polynomial

int coefficient;

int exponent;

struct polynomial *next;

};

Thus the above polynomial may be represented using linked list as shown below:

Addition of two Polynomials:


 For adding two polynomials using arrays is straightforward method, since both the arrays
may be added up element wise beginning from 0 to n-1, resulting in addition of two
polynomials.
 Addition of two polynomials using linked list requires comparing the exponents, and
wherever the exponents are found to be same, the coefficients are added up.
 For terms with different exponents, the complete term is simply added to the result thereby
making it a part of addition result.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 3 /ANSWER
Page 13 of 13
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

USCS 33- DATA STRUCTURES


Unit – IV
Answer Bank

UNIT IV: Trees: Binary Trees – Operations – Recursive Tree Traversals.

SECTION – A
(2 Marks)
1. What is Tree? Nov/Dec 2015 Apl/May 2015
A tree T is a finite, non-empty set of nodes.
T={r} U T1 U T2 U…….U Tn;
Properties:
1. A designated node of the set, r is called the root of the tree.
2. Remaining nodes are partitioned into n>=0 subsets, T1,T2…..Tn each of
which is a tree.
T= {R, T1, T2…..Tn} to denote the tree T.

2. Define the term: Binary Tree Nov 2014 April 2011 Nov 2010
A binary tree T is a finite set of nodes.
Properties:
1. Either the set is empty, T=NULL ; or
2. The set consists of a root, r, and exactly two distinct binary trees
TL and TR, T={r, TL,TR}.

3. Draw an example of Tree and Binary Tree.


Tree: Binary Tree:

A A
B D C
B
C E F
D E F G

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 1 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

4. What are the operations on Binary Tree? Nov/Dec 2013


Inorder : Visit left subtree, visit root, visit right subtree.
Preorder : visit root, visit left, visit right.
Postorder : visit left, visit right, visit root.

5. Define BST.
A binary search tree is a rooted binary tree, whose internal nodes each store
a key (and optionally, an associated value) and each have two distinguished sub-trees,
commonly denoted left and right.

6. Write a procedure for Recursive Preorder Tree Traversal Techniques. Nov


2010
Definition : Print out all the elements in the binary search tree in order from
smallest to largest.
Size : Nodes in the whole tree.
Base case : When P=NULL, do nothing.
General case : Traverse the left subtree in order.
Print INF(P)
Traverse the right subtree in order.

7. What is Degree?
Degree of a node is the number of subtrees associated with that node.
T={r,T1,T2,……,Tn},n>=0
E.g., the degree of tree T is n

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 2 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

8. What is Siblings? Apl/May 2015


Two roots ri and rj of distinct subtrees Ti and Tj of tree T are called siblings.
Nodes with the same parent.
Eg:
A

B C D
1
Here, A! is the parent of B, C, and D. so B, C and D are the siblings.
1

9. What are Leaf, Ancestor, and Descendant?


Leaf – a node with no children
Descendant – a node reachable by repeated proceeding from parent
to child.
Ancestor – a node reachable by repeated proceeding from child to
parent.
10. What is Height and Depth of a node?

Height of node – The height of a node is the number of edges on the longest
downward path between that node and a leaf.

Depth of node – The depth of a node is the number of edges from the node to the
tree's root node.

11. What is an Internal and External node?

Internal node – a node with at least one child.

External node – a node with no children.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 3 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

12. Write two properties of Binary Tree?

1. Either the set is empty, T=NULL ; or


2. The set consists of a root, r, and exactly two distinct binary trees TL and
TR, T={r, TL, TR}.
13. Define N-ary Tree?
An N-ary tree T is a finite set of nodes
Properties:

a. Either the set is empty, T=NULL ; or


b. T={R,T0,T1,…,TN-1}

14. Draw an Example of Two Distinct Binary Trees?

A A

B B

15. What are Out Degree and In Degree of a node?


Out Degree : The number of nodes connected to a node
In Degree : The number of immediate preceding nodes.

16. What are Left and Right Sub Tree?


A subtree of a tree T is a tree consisting of a node in T and all of its
descendants in T
Left Sub Tree : The Left side of the root.
Right Sub Tree : The Right side of the root.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 4 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

17. What are the three basic fields in each node of a Tree?
1. INFO(P) – contains the data stored in the linked list pointed to by P.
2. LEFT(P) – A pointer to the left child of the node pointed to by P.
3. RIGHT(P) – A pointer to the right child of the node pointed to by P.

18. What is Tree Traversal? Nov/Dec 2015


The process of walking through the tree is called a tree traversal.
i.e To visit all the nodes in a tree.
Eg: To print all the values in the tree.

19. What is Preorder Traversal?


The First Depth-first traversal method is called Preorder traversal
Preorder : Visit root, visit left, visit right.

Eg : (MABT) Root Left Right

A T

20. What is Postorder Traversal?


The Second Depth-first traversal method is called Preorder traversal
Postorder : visit left, visit right, visit root.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 5 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

Eg : (BATM) Left Right Root

A T

21. What is Inorder Traversal?


The Third Depth-first traversal method is called Inorder traversal
Inorder : Visit left subtree, visit root, visit right subtree.

Eg : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

22. Draw an example for Converting Forest in to Binary Trees?

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 6 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

23. What is Path and Path Length?

Path – a sequence of nodes and edges connecting a node with a descendant.

Path Length – Number of Edges.

24. What are Subtree and its diagram?

The tree which is a child of a node.

25. What are Descendant and Ancestor?

Descendant – a node reachable by repeated proceeding from parent to child.

Ancestor – a node reachable by repeated proceeding from child to parent.

SECTION – B
(5 Marks)

1. Explain Inorder Tree Traversal Technique using Recursion (Nov 2010)


Inorder Tree Traversal :

The third depth-first traversal method is inorder traversal.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 7 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

Visit left subtree, visit root, visit right subtree.

a. Traverse the left subtree by recursively calling the in-order function


b. Display the data part of root element (or current element)
c. Traverse the right subtree by recursively calling the in-order function

Procedure IN-Order :

Definition : Print out all the elements in the binary search tree in
order from smallest to largest.
Size : Nodes in the whole tree.
Base case : When P=NULL, do nothing.
General case : Traverse the left subtree in order.
Print INF(P)
Traverse the right subtree in order.
Example for IN-ORDER Tree Traversal:

F S

B H R V

G T Z

In - Order : BFGHPRSTWYZ

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 8 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

2. Explain Postorder Tree Traversal Technique using Recursion


Postorder Tree Traversal : visit left, visit right, visit root.

The second depth – first traversal method is post order traversal.

In General Tree :

1. Do a postorder traversal each of the subtrees of the root one-by-one in the


order.
2. Visit the root.

In Binary Tree :

1. Traverse the left subtree.


2. Traverse the right subtree.
3. Visit the root.

Example for IN-ORDER Tree Traversal:

F S

B H R V

G T Z

Post - Order : BGHFRWTZYSP


RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 9 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

3. Discuss about the N-ary Trees.


Definition (N-ary Tree) : An N-ary tree T is a finite set of nodes .
Properties:

1. Either the set is empty, T = NULL; or


2. The set consists of a root, R, and exactly N distinct N-ary trees. That is, the
remaining nodes are partitioned into n>=0 subsets, T0 ,T1 , ..., Tn-1, each of
which is an N-ary tree such that T = {R,T0,T1,…,Tn-1}

 According to Definition , an N-ary tree is either the empty tree, Null , or it is


a non-empty set of nodes which consists of a root and exactly N subtrees.
 Clearly, the empty set contains neither a root, nor any subtrees.
 Therefore, the degree of each node of an N-ary tree is either zero or N.
 The empty trees are called external nodes.
 The non-empty trees are called internal nodes .
Figure: Examples of N- ary trees.
Ta = {B, {C, null, null, null}, null, null}

4. Explain various operations on Binary Tree Nov 2014 & 2015 April 2011
Binary Tree : A binary tree T is a finite set of nodes.
Two Operations :
 Inserting into binary search tree.
 Deleting from a binary search tree.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 10 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

Inserting into binary search tree:


To create and maintain a binary search tree, it is necessary to have a
routine that will insert new nodes into the tree.

a) ROOT -> NIL b)Insert 9 c)Insert 7

5 5 5

9
9

1. Create a node for the new value.


2. Search for the insertion place.
3. Fix pointers to insert new node.
Deleting from a Binary Search Tree:
1. Deleting a leaf (no children)
2. Deleting a node with only one child
3. Deleting a node with two children.
a) The initial tree b) Delete J

L L

N P N P

C H C H

A F J A F

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 11 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

c) Delete C d) Delete L

L H

N P N P

A H
A F

5. Write the Terminologies used in Trees.

 Root – The top node in a tree.


 Parent – The converse notion of child.
 Siblings – Nodes with the same parent.
 Descendant – a node reachable by repeated proceeding from parent to child.
 Ancestor – a node reachable by repeated proceeding from child to parent.
 Leaf – a node with no children.
 Internal node – a node with at least one child.
 External node – a node with no children.
 Degree – number of sub trees of a node.
 Edge – connection between one node to another.
 Path – a sequence of nodes and edges connecting a node with a descendant.
 Level – The level of a node is defined by 1 + (the number of connections between the
node and the root).
 Height of tree –The height of a tree is the number of edges on the longest downward
path between the root and a leaf.
 Height of node –The height of a node is the number of edges on the longest
downward path between that node and a leaf.
RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 12 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

 Depth –The depth of a node is the number of edges from the node to the tree's root
node.
 Forest – A forest is a set of n ≥ 0 disjoint trees.

6. Draw a Binary Tree Construction Apl/May 2015


a) Input : 4 2 6 1 3 5 7
b) Input : 2 1 4 3 7 6 5
c) Input : 1 2 3 4 5 6 7
a) Input : 4 2 6 1 3 5 7 b) Input : 2 1 4 3 7 6 5

4 2

2 6 1 4

3 7
1 3 5 7

5
b) Input : 1 2 3 4 5 6 7

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 13 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

PART – C QUESTIONS
1. Explain the functioning of Tree Traversal Methods in Detail? Nov 2014 Nov/Dec 2013
Tree Traversal:

The process of walking through the tree is called a tree traversal.


i.e To visit all the nodes in a tree.
Eg: To print all the values in the tree.
Traversal Methods:
 Preorder Traversal
 Postorder Traversal
 Inorder Traversal
Preorder Traversal Methods:
The First Depth-first traversal method is called Preorder traversal
Preorder : Visit root, visit left, visit right.

Procedure:

void preorder(tree_pointer ptr)


/* preorder tree traversal */
{
if (ptr) {
printf(“%d”, ptr->data);
preorder(ptr->left_child);
predorder(ptr->right_child);
}
}

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 14 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

Eg : (MABT) Root Left Right

A T

Postorder Traversal Methods:


The Second Depth-first traversal method is called Postorder traversal
Postorder : visit left, visit right, visit root.

Procedure:
void postorder(tree_pointer ptr)
/* postorder tree traversal */
{
if (ptr) {
postorder(ptr->left_child);
postdorder(ptr->right_child);
printf(“%d”, ptr->data);
}
}
Eg : (BATM) Left Right Root

A T

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 15 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

Inorder Traversal Methods:


The Third Depth-first traversal method is called Inorder traversal
Inorder : Visit left subtree, visit root, visit right subtree.
Procedure:
void inorder(tree_pointer ptr)
/* inorder tree traversal */
{
if (ptr) {
inorder(ptr->left_child);
printf(“%d”, ptr->data);
indorder(ptr->right_child);
}
}
Eg : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

2. Explain Binary Search Tree? Nov 2014


Binary Search Tree, is a node-based binary tree data structure .
Properties:
 The left subtree of a node contains only nodes with keys less 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.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 16 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

There must be no duplicate nodes.

 The above properties of Binary Search Tree provide an ordering among keys so that
the operations like search, minimum and maximum can be done fast.
 If there is no ordering, then we may have to compare every key to search a given key.
Searching a key:
To search a given key in Bianry Search Tree, we first compare it with root, if the key
is present at root, we return root.
 If key is greater than root’s key, we recur for right subtree of root node. Otherwise we
recur for left subtree.

// C function to search a given key in a given BST


struct node* search(struct node* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);

// Key is smaller than root's key


return search(root->left, key);
}

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 17 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

Insertion of a key

 Once a leaf node is found, the new node is added as a child of the leaf node.
 A new key is always inserted at leaf.
 We start searching a key from root till we hit a leaf node.

100 100

/ \ Insert 40 / \

20 500 ---------> 20 500

/ \ / \

10 30 10 30

40

Deletion from key


 Node to be deleted is leaf : Simply remove from the tree.
50 50

/ \ delete(20) / \

30 70 ---------> 30 70

/ \ / \ \ / \

20 40 60 80 40 60 80

 Node to be deleted has only one child: Copy the child to the node and delete the
child
50 50

/ \ delete(30) / \

30 70 ---------> 40 70

\ / \ / \

40 60 80 60 80

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 18 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

 Node to be deleted has two children: Find inorder successor of the node. Copy
contents of the inorder successor to the node and delete the inorder successor. Note
that inorder predecessor can also be used.
50 60

/ \ delete(50) / \

40 70 ---------> 40 70

/ \ \

60 80 80

3. a) Discuss about the Recursive Tree Traversals Apl/May 2015


b) Define forest and Draw an example for Converting Forest in to Binary Trees
Nov/Dec 2015
a)
Procedure In-Order:
Each node was visited in between its left and right subtrees.
Definition : Print out all the elements in the binary search tree in
order from smallest to largest.
Size : Nodes in the whole tree.
Base case : When P=NULL, do nothing.
General case : Traverse the left subtree in order.
Print INF(P)
Traverse the right subtree in order.
Other Tree Traversal Orders:
Preorder Traversal : Visits each node before its left and right
subtrees.
A preorder traversal of a binary tree:
1. Visits the root.
2. Traverses the left subtree pre-order.
3. Traverses the right subtree pre-order.
Postorder Traversal : Visits each node after its left and right
subtrees.
RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 19 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

A postorder traversal of a binary tree:


1. Traverses the left subtree post-order.
2. Traverses the right subtree post-order.
3. Visits the roots.

F S

B H R Y

G T Z

In-Order : B F G H P R S T W Y Z
Pre-Order : P F B H G S R Y T W Z
Post-order : B G H F R N T Z Y S P

b) Forest:

A forest is a set of n ≥ 0 disjoint trees.

A forest is an (ordered) set of zero or more general trees.

A General Tree = A One-Tree Forest.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 20 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

Converting Forest in to Binary Trees:

4. Explain about the Binary Trees.


A binary tree T is a finite set of nodes.
Properties:
1. Either the set is empty, T=NULL ; or
2. The set consists of a root, r, and exactly two distinct binary trees
TL and TR, T={r, TL,TR}.
 The tree TL is called the left subtree of T, and the tree TR is called the right subtree
of T.
 Binary Trees are considered to be ordered trees.
Eg: Two Distinct Binary Trees

A A

B B

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 21 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

A Binary tree with n>=0 internal nodes contains n+1 external nodes.

The number of nodes pointing should be less than or equal to two, then tree is said to
be Binary Tree.

Diagram of Binary Tree:

r
d

a e n s

Out degree of a node : The number of nodes connected to a node.


In degree of a node : The number of immediate preceding nodes.
Node M is called the Root .
Left subtree : Left side of the root.
Right subtree : Right side of the root.
Siblings : Nodes with the same parent eg: (a,e),(n,s)
Ancestor : Two Parent nodes.
Descendant : Two child nodes.

Left subtree Right subtree

r
d

a e n s

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 22 of 23
ACADEMIC YEAR: 2015 – 2018 REGULATION CBCS - 2012

 The number of maximum possible nodes at a particular level can be calculated


by using 2n , where n is the level number.
 So, the possible node at level 2 is 4. i.e (22)

 If all the parents have 2 childrens, then the tree is said to be a complete tree.
 If all the parents have not 2 childrens, then the tree is said to be an Incomplete
tree.
 The left child of any parent will store the value lesser than its parent.
 The Right child of any parent will store the values greater than its parent.
Example of Binary Tree construction:

a) Input : 4 2 6 1 3 5 7

2 6

1 3 5 7

Three basic fields in each node of a tree:

1.INFO(P) – contains the data stored in the linked list pointed to by P.


2.LEFT(P) – A pointer to the left child of the node pointed to by P.
3.RIGHT(P) -- A pointer to the right child of the node pointed to by P.

RAAK / BSC (CS) / C. VICTOR VIMAL RAJ / II YEAR / III SEM /DATA STRUCTURES
USCS33 / UNIT- 4 /ANSWER
Page 23 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

USCS33 – DATA STRUCTURES


Unit – 5 Graphs, sorting and searching
Questions and Answers

Syllabus:

UNIT V: Trees: Graph – Definition, Types of Graphs, Graphs Traversal – DFS and BFS.
Sorting by selection – Sorting by exchange (Bubble) – Sorting by insertion – Linear
Search – Binary Search.

PART – A QUESTIONS

1. Define Searching. Nov 2010, Apl 2015


Searching is any data structure that allows the efficient retrieval of specific items
from a set of items, such as a specific record from a database.
Techniques
 Sequential search(Linear search)
 Index sequential search(File)
 Binary search

2. Define Graph. April 2011

• A graph G = (V,E) is composed of:


V: set of vertices
E: set of edges connecting the vertices in V
• An edge e = (u,v) is a pair of vertices
• Example:

a b V= {a,b,c,d,e}

E=
c {(a,b),(a,c),(a,d),
(b,e),(c,d),(c,e),
(d,e)}
d e

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 1 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

3. Write any 2 applications of graph.


 Electronic circuits
 Networks (roads, flights, communications)

4. List the types of graphs traversals Nov/Dec 2013


BFS(Breadth first search) – The aim of BFS algorithm is to traverse the graph
as close as possible to the root node.
DFS(Depth first search) – The aim of DFS algorithm is to traverse the graph in
such a way that it tries to go far from the root node.

5. What is directed & directed graph ?


 An undirected graph is one in which the pair of vertices in a edge is unordered,
(v0, v1) = (v1,v0)
 A directed graph is one in which each edge is a directed pair of vertices, <v0, v1>
!= <v1,v0>

6. What is directed & directed edge?


 In a graph, every edge directed to one node to another is called directed edge.
 The graph in which the edges are not directed is called directed edge.

7. What is mixed graph & multi graph?


 In a graph, if some are directed and some are undirected, then the graph is called
the mixed graph.
 A graph which contains parallel edges are called multigraph.

8. What is simple and weighted graph?


 A graph which does not contain parallel edges are called simple graph.
 If every edge carries some value, then it is said to be a weighted graph.

9. What is isolated node and multi graph?

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 2 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 A node which is not adjacent to any other node is called isolated node.
 A graph which contains only isolated node is called null graph.
10. Define path and path length.
A path in a directed graph G=(V,E) is a non-empty sequence of vertices
P={v1;v2…….vk}
Where vi belongs to V for 1<=i<=k such that (vi,vi+1) belongs to E for 1<=i<=k.
The length of path p is k-1.
11. What is cycle and loop in graph?
 A cycle is a path P of non-zero length in which v1=vk. The length of a cycle is just
the length of the path P.
 A loop is a cycle of length one. i.e. it is a path of the form {v,v}

12. Define DAG.


DAG-Directed, acyclic graph is a directed graph that contains no cycles.
Directed Acyclic graphs.

b c

13. Define BFS with example.


The aim of BFS algorithm is to traverse the graph as close as possible to the root
node.
B D

A C E

S F

RAAK/BSC.CS /C VICTOR
G VIMAL RAJ/II
H YEAR/III Sem/USCS33
DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 3 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Output : ABSCGDEFH

14. Define DFS with example.


The aim of DFS algorithm is to traverse the graph in such a way that it tries to go
far from the root node.
B D

A C E

S F

G H

Output : ABSCDEHGF

15. Define sorting and its types.


Rearranging the elements or value either ascending or descending.
Types:
 Internal sorting - Internal Sorting takes place in the main memory of a
computer
 External sorting - External sorting, takes place in the secondary memory
of a computer, since the number of objects to be sorted is too large to fit in
main memory.

16. What are the advantages of quick sort? April 2012


 Efficient average case compared to any sort algorithm
 It is faster than O(NlogN).
 Better cache performance and high speed.

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 4 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

17. What is an insertion sort? Nov 2012


 Insertion sort is a simple sort algorithm, a comparison sort in which the sorted
array (or list) is built one entry at a time.
Analysis of insertion sort
 Worst case analysis o(n2)
 Best case analysis o(n)
 Average case analysis o(n2)

18. Name some internal and external sorting methods.


Internal sorting:
Bubble sort, Insertion sort, Selection sort, Quick sort, Heap sort, etc.
External sorting:
Merge Sort, Multiway Merge, Polyphase merge, Index sequential and random
access.

19. What do you mean by linear search? April 2011


 Linear search is the simplest search algorithm.
 Linear search or sequential search is a method for finding a particular value in
a list that checks each element in sequence until the desired element is found.

20. Define quick sort. April 2011,2016


 It is also called partitioning sort which uses divide and conquer techniques.
 The quick sort works by partitioning the array A[l], A[2]….A[n] by picking some
key value in the array as a pivot element.
 Pivot element is used to rearrange the elements in the array.

21. Define Bubble sort.


 Bubble sort is a simple and well-known sorting algorithm.
 Bubble sort is quite inefficient for sorting large data volumes.
 Bubble sort is stable and adaptive.

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 5 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

22. Write the average and best case analysis of insertion sort. Nov/Dec 2011
 Average case analysis O(N2)
 Best case analysis O(N)
It is simple to implement and efficient on small data sets and expensive

23. What is merge sort?


 Mergesort is a sorting algorithm for rearranging lists (or any other data structure
that can only be accessed sequentially, e.g. file streams) into a specified order.
 It is a particularly good example of the divide and conquer algorithmic
paradigm.
 It is a comparison sort.

24. What is selection sort?


 Selection sort algorithm is an easy-to-program, but very inefficient sorting
algorithm.
 Selection sort is quite inefficient for sorting large data volumes.
 Selection sort is notable for its programming simplicity

25. Write any two applications of searching and sorting.


 Telephone Directory.
 Dictionaries.
 Large set of data in computers.

PART – B QUESTIONS
1. Explain the following Nov 2010
a) BFS
b) DFS Nov 2010
a) BFS - Breadth First Search

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 6 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

The aim of BFS algorithm is to traverse the graph as close as possible to the root
node.
BFS is one of the types of graph traversal.
 Go to all nearest nodes first.
 The data structure “queue” is used to store the visited nodes.
 Expand from visited (but not dead) nodes.
Algorithm: while queue Q not empty
dequeue the first node u from Q
for each adjacent node v from u
if v is unvisited
enqueue v to Q
mark v as visited
 Initialize all nodes as unvisited, except the starting node
Advantages
 Shortest route is guaranteed on unweighted graphs
 Avoid stack overflow
Example:
B D

A C E

S F

G H

Output : ABSCGDEFH
b) DFS - Depth-First-Search

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 7 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 The aim of DFS algorithm is to traverse the graph in such a way that it
tries to go far from the root node.
 DFS is one of the types of graph traversal.
 Once a possible path is found, continue the search until the end of the path
Algorithm:
DFS (node u) {
mark u as visited
for each adjacent node v from u
if (v is unvisited) DFS (v)
}
 Initialize all nodes as unvisited
Advantages
 Useful for checking whether 2 nodes are connected.
Drawbacks
 Finding a shortest path using DFS is difficult.
 Stack overflow.

Example:

B D

A C E

S F

G H

Output : ABSCDEHGF

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 8 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

2. Explain insertion sort with example. Nov 2010


 Insertion sort is a simple sort algorithm, a comparison sort in which the sorted array (or
list) is built one entry at a time. It is much less efficient on large lists than the more
advanced algorithms such as quicksort, heapsort, or merge sort, but it has various
advantages.
 In abstract terms, each iteration of an insertion sort removes an element from the input
data, inserting it at the correct position in the already sorted list, until no elements are left
in the input.
The strategy:
Given : A - set of unsorted array elements.
N - Number of elements
1. In the given array each element is considered as key element in the sequential order.
2. To get the algorithm started, consider that the first element alone exists in a sorted
segment.
3. Now consider the key element (i.e. second element) and compare the key element with the
proceeding sub array element (i.e. first element), if it is greater rearrange the position (i.e.
key element is stored at the correct position)
4. The general idea is to increase the length of the stored segment by inserting the next
element in the proper place until N elements, to derive a sorted list of elements.
Insertion Sort Procedure:
void insertionsort (int a[ ], int n)
{
int i,j, temp;
for(i = l; i < n; i++)
{
temp=a[i];
for(j = i; j > 0; j--)
if (a[j-l] > temp)
a[j]=a[j-l];

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 9 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

a[j] = temp;
}
}

ANALYSIS OF INSERTION SORT


WORST CASE ANALYSIS O(N2)
BEST CASE ANALYSIS O(N)
AVERAGE CASE ANALYSIS O(N2)
ADVANTAGES OF INSERTION SORT :
 Simple to implement
 Efficient on (quite) small data sets
 Efficient on data sets which are already substantially sorted
 Stable
 Does not suffer from poor "worst case input" performance
 Minimal memory requirements
LIMITATIONS OF INSERTION SORT :
 It is relatively efficient for small lists and mostly - sorted lists.
 It is expensive because of shifting all following elements by one.

3. Describe linear searching. Nov 2010


 In Linear Search the list is searched sequentially and the position is returned if the key
element to be searched is available in the list, otherwise -1 is returned.
 The search in Linear Search starts at the beginning of an array and move to the end,
testing for a match at each item.
 All the elements preceding the search element are traversed before the search element is
traversed. i.e. if the element to be searched is in position 10, all elements form 1-9 are
checked before 10.

Algorithm : Linear search implementation

bool linear_search ( int *list, int size, int key, int* rec )

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 10 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

// Basic Linear search

bool found = false;

int i;

for ( i = 0; i < size; i++ )

if ( key == list[i] )

break;

if ( i < size )

found = true;

rec = &list[i];

return found;

Example:

Assume the element 45 is searched from a sequence of sorted elements 12, 18, 25, 36, 45,
48, 50.

The Linear search starts from the first element 12, since the value to be searched is not
12 (value 45), the next element 18 is compared and is also not 45, by this way all the elements
before 45 are compared and when the index is 5, the element 45 is compared with the search
value and is equal, hence the element is found and the element position is 5.

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 11 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

4. Write an algorithm for quick sort and explain it with an example. April 2012,2015

 Quick Sort is the most efficient internal sorting technique.


 It possesses a very good average case behavior among all the sorting techniques.
 It is also called partitioning sort which uses divide and conquer techniques.
 The quick sort works by partitioning the array A[l], A[2] A[n] by picking some key
value in the array as a pivot element.
 Pivot element is used to rearrange the elements in the array.
 Pivot can be the first element of an array and the rest of the elements are moved so that
the elements on left side of the pivot are lesser than the pivot, whereas those on the
right side are greater than the pivot.
 Now, the pivot element is placed in its correct position.
 Now the quicksort procedure is applied for left array and right array in a recursive
manner.
Given an array of n elements (e.g., integers):
 If array only contains one element, return
 Else
 Pick one element to use as pivot.
 Partition elements into two sub-arrays:
 Elements less than or equal to pivot
 Elements greater than pivot
 Quicksort two sub-arrays

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 12 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 Return results

void qsort(int a[],int left,int while(a[pivot]<a[j])


right) j=j-1;
{ if(i<j)
int i,j,pivot,temp;
{temp=a[i];
if(left<right) a[i]=a[j];
{ a[j]=temp;
pivot=left;
}
i=left+1; }
j=right; temp=a[pivot];
while(i<j)
a[pivot]=a[j];
{ a[j]=temp;
while(a[pivot]>=a[i]) qsort(a,left,j-1);
i=i+1; qsort(a,j+1,right);
20
}

Quick sort Analysis:


ANALYSIS OF QUICK SORT:
WORST CASE ANALYSIS O(N2)
BEST CASE ANALYSIS O(N log N)
AVERAGE CASE ANALYSIS O(N log N)
ADVANTAGES OF QUICK SORT :
 It is faster than other O(NlogN) algorithms.
 It has better cache performance and high speed.
LIMITATIONS OF QUICK SORT :
 It requires more memory space.

5. Explain about the selection sort with example.


 Selection sort algorithm is an easy-to-program, but very inefficient sorting algorithm.
 Selection sort is quite inefficient for sorting large data volumes.
 Selection sort is notable for its programming simplicity
Algorithm:
 1st iteration selects the smallest element in the array, and swaps it with the first element.
 2nd iteration selects the 2nd smallest element (which is the smallest element of the
remaining elements) and swaps it with the 2nd element.

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 13 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 The algorithm continues until the last iteration.


 The idea of algorithm is quite simple.
 Array is imaginary divided into two parts - sorted one and unsorted one.
 At the beginning, sorted part is empty, while unsorted one contains whole array.
 At every step, algorithm finds minimal element in the unsorted part and adds it to the end
of the sorted one.
 When unsorted part becomes empty, algorithm stops.
 When algorithm sorts an array, it swaps first element of unsorted part with minimal
element and then it is included to the sorted part.

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 14 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Analysis of Selection Sort:


 Worst-case, Average-case, and Best-case run-time of O(N2)
Advantages of the Selection Sort:
 The selection sort is easy to understand
 It is easy to implement the algorithm correctly
 The sorting procedure is easy to write

Disadvantages of the Selection Sort:


 Require large amounts of memory
 Quite slow on large amounts of data.

PART – C QUESTIONS

1. Define graph and explain the properties of the graph.


Graph:

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 15 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

• A graph G = (V,E) is composed of:


V: set of vertices
E: set of edges connecting the vertices in V
• An edge e = (u,v) is a pair of vertices
• Example:

a b V= {a,b,c,d,e}

E=
c {(a,b),(a,c),(a,d),
(b,e),(c,d),(c,e),
(d,e)}
d e

Properties of Graph:
1. Complete Graph:
Complete graph is a graph in which there is an edge between every pair of vertices.
A complete graph with n vertices will have n(n-1)/2 edges.

V1 V2

V3 V4

2. Sub Graph:
A subgraph G’ of G is a graph G such that the set of vertices and set of edges of G’ are
proper subset of the set of edges of G.
G G’
V1 V1

V2 V3 V2

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 16 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

3. Connected Graph:
Any two vertices are connected by some path.

Connected Not connected


4. Strongly Connected Graph:
A directed graph is said to be strongly connected if and only if, for each pass of distinct
vertices Vi and Vj, there is a path from vi to vj in G.

V1 V2

V3 V4

5. Cyclic Graph:
A directed graph is said to be a cyclic graph in which no vertex is repeated except the
first and last vertex are the same.

B C

Cycle : A-> B->C->A

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 17 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

6. Acyclic Graph:
A graph is said to be a cyclic graph if it has no cycles.
Directed Acyclic Graph(DAG):

A C

B
Undirected Acyclic Graph:
A C

7. Weighted Graph:
A graph is said to be weighted graph if every edge in the graph is assigned a weight or
value.
It can be either a directed or an undirected graph.
15
A C
10

1
A C
9

8. Bioconnectivity:
A bioconnectivity graph are graphs which cann’t be broke into disconnected graphs by
disconnectivity single edge.
If we remove any single edge the graph the graph does n’t become disconnected.
Example:
E1
V1 V2
RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33
V5
DATA STRUCTURES/UNIT-5 Q&A
V3 V4
Unit – 5 Q & A Page 18 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

E5
E2 E3

E4 E6

V1 V2 E5

V5
E2 E3
V3 V4
E4 E6

2. Describe merge sort with example. Nov 2010


 In computer science, merge sort or mergesort is a sorting algorithm for rearranging lists
(or any other data structure that can only be accessed sequentially, e.g. file streams) into a
specified order.
 It is a particularly good example of the divide and conquer algorithmic paradigm. It is a
comparison sort.
 Conceptually, merge sort works as follows:
 Divide the unsorted list into two sublists of about half the size
 Sort each of the two sublists
 Merge the two sorted sublists back into one sorted list.
 The algorithm was invented by John von Neumann in 1945.
The strategy:
1. Merge sort divides the array into two equal halves and sorts the halves separately (using
recursion), then it merges the sorted halves.
2. The parameters used for merge are: the array name A , and the left, center and right
indexes of the subranges to merge; that is the two sorted sub ranges are A[left]… A
[center+1] ... A[right] (after recursion), and the final sorted array is A[left] ... A[right].

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 19 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

ANALYSIS OF MERGE SORT


WORST CASE ANALYSIS O(N LOG N)
BEST CASE ANALYSIS O(N LOG N)
AVERAGE CASE ANALYSIS O(N LOG N)
Limitations of Merge Sort:
 Mergesort sorts the larger amount of data making use of external storage device.
 It requires extra memory space.
Advantages
 It has better cache performance.
 Merge Sort is a Stable Sort.
 It is simpler to understand than heapsort.

3. Explain the binary search method.

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 20 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 All of the sequential search algorithms have the same problem; they walk over the entire
list.
 Some of our improvements work to minimize the cost of traversing the whole data set,
but those improvements only cover up what is really a problem with the algorithm.
 By thinking of the data in a different way, we can make speed improvements that are
much better than anything sequential search can guarantee.
 Consider a list in ascending sorted order. It would work to search from the beginning
until an item is found or the end is reached, but it makes more sense to remove as much
of the working data set as possible so that the item is found more quickly.
 If we started at the middle of the list we could determine which half the item is in
(because the list is sorted).
 This effectively divides the working range in half with a single test. By repeating the
procedure, the result is a highly efficient search algorithm called binary search.
 The actual algorithm is surprisingly tricky to implement considering the apparent
simplicity of the concept.
 The necessity of this method is that all the elements should be sorted.

-40 11 33 37 42 45 99 100

 Now the key element which is to searched is 99. Key =99.


 Find the middle element of the array compare it with the key.

Algorithm:

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 21 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

if(low>high)
Return;
Mid=(low+high)/2;
If(x==a[mid])
Return(mid);
If(x<a[mid])
Search for x in a[low] to a[mid-1];
Else
Search for x in a[mid+1] to a[high];

4. Describe bubble sort with example. April 2011,2016


 Bubble sort is a simple and well-known sorting algorithm.
 Bubble sort is quite inefficient for sorting large data volumes.
 Bubble sort is stable and adaptive.
Algorithm
 Compare each pair of adjacent elements from the beginning of an array and, if they are in
reversed order, swap them.
 If at least one swap has been done, repeat step 1.
 Example. Sort {5, 1, 12, -5, 16} using bubble sort.
bubblesort (int a[],int n)
{
int tmp,i,j;
for (i=0; i<n-1; i++)
{
for (j=0; j<n-i-1; j++)
if (a[j] > a[j+1])
{
tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 22 of 23
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

}
}
}

Analysis of Bubble sort:


WORST CASE ANALYSIS O(N2)
BEST CASE ANALYSIS O(N)
AVERAGE CASE ANALYSIS O(N2)
Advantages of Bubble sort:
 It is very simple to understand and implement.
 It is a stable sort that requires no additional memory
Disadvantages of Bubble sort:
 This sort requires several passes over the data, and thus its efficient.
Turtles and rabbits
 One more problem of bubble sort is that its running time badly depends on the initial
order of the elements.
 Big elements (rabbits) go up fast, while small ones (turtles) go down very slow.

RAAK/BSC.CS /C VICTOR VIMAL RAJ/II YEAR/III Sem/USCS33


DATA STRUCTURES/UNIT-5 Q&A
Unit – 5 Q & A Page 23 of 23

You might also like