Q 1. What Is Data Structure? Also Define Structures and Operations

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 47

YEAR 2014

Q 1. What is data structure? Also define structures and operations.

Definition: Data structure is a specialized format for organizing and storing


data. i.e. data structure is a particular way of organizing data in a computer so that it
can be used efficiently.
Types of data Structure:
There are two types of data structure.
1. Linear data structure.
2. Non-linear data structure.

1. Linear data Structure: In linear data structures, values are arranged in


linear fashion. i.e. data is processes sequentially.
Example of linear data Structure:
1. Stack: In Stack data is arranges in LIFO fashion. i.e. Last In First Out.

Push is putting data into stack and POP is removing data from Stack.
2. Queue: In Queue data is arranged in FIFO fashion. i.e. First In First Out.

3. Linked List: A linked list is a finite sequence of nodes each of which contains
a pointer field pointing to the next node.

4. Array: Array is a collection of elements, each identified by at least one


index key.

2.Non-linear data Structure: A non-linear data structure is a data structure


in which a data item is connected to several other data items. So that a given
data item has the possibility to reach one-or-more data items. These are not
arranged sequentially.
Examples of Non-linear data Structure:
1. Tree: A connected, undirected, acyclic graph. It is rooted and ordered
unless otherwise specified.

2.Graph: A set of items connected by edges. Each item is called a vertex


or node.

Operations in data Structure:


There are 6 Major operations that can be performed in data structures:
1. Traversing
2. Searching
3. Inserting

4. Deleting
5. Sorting
6. Merging
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. Inserting- It is used to add a new data item in the given collection of data
items.
4. Deleting- 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.

Q2.Compare between array and linked list. Also define types of linked list.

Define

Array is a collection of
elements having same
data type with common
name.

Access

In array, elements can be


accessed using
In linked list, elements cant be accessed
index/subscript value, i.e.
randomly but can be accessed
elements can be randomly
only sequentially and accessing element
accessed like arr[0], arr[3],
takes 0(n) time.
etc. So array provides fast
and random access.

Memory
Structure

Insertion &

Linked list is an ordered collection of


elements which are connected by
links/pointers.

In array, elements are


In linked list, elements can be stored at
stored
any available place as address of node is
in consecutive manner in
stored in previous node.
memory.
Insertion & deletion takes Insertion & deletion are fast & easy in

Deletion

Memory
Allocation

Types

more time in array as


elements are stored in
consecutive memory
locations.

In array, memory is
allocated at compile time In linked list, memory is allocated at run
i.e. Static Memory
time i.e. Dynamic Memory Allocation.
Allocation.
Array can be single
dimensional, two
dimension or
multidimensional.

In array, each element is


independent, no
Dependency connection with previous
element or with its
location.

Extra Space

linked list as only value of pointer is


needed to change.

In array, no pointers are


used like linked list so no
need of extra space in
memory for pointer.

Linked list can


be singly, doubly or circular linked list.

In Linked list, location or address of


elements is stored in the link part of
previous element/node.
In linked list, adjacency between the
elements are maintained using pointers or
links, so pointers are used and for that
extra memory space is needed.

Types of linked lists: There are three types of Linked lists:


1. Linear Linked List or One Way List or Singly Linked List
2. Doubly Linked List or Two-Way Linked List.
3. Circular Linked List

1. Linear Linked List or One Way List or Singly Linked List


It is linear collection of data elements which are called Nodes. Each node is
divided into two parts. The first part contains the information of the element
and is called INFO Field. The second part contains the address of the next
node and is called LINK Field or NEXT Pointer Field. The START contains the
starting address of the linked list.

2.

Doubly Linked List:


In it each node is divided into three parts:
1. The first part is PREV part. It is previous pointer field. It contains the address
of the node which is before the current node.
2. The second part is the INFO part. It contains the information of the element.
3. The third part is NEXT part. It is next pointer field. It contains the address of
the node which is after the current node.

3. Circular Linked List: In it the last node does not contain NULL pointer. Instead
the last node contains a pointer that has the address of first node and thus
points back to the first node.

Q3.What is recursion? Explain the applications of recursion.

Definition: Recursion is an approach in which a function calls itself with an


argument. Upon reaching a termination condition, the control returns to the
calling function.

Example of recursion a function that calls another function which in turn


calls it again.

int function(int value) {


if(value < 1)
return;
function(value - 1);

printf("%d ",value);
}

Applications of recursion:

To navigate through disk directory trees

Parse binary trees

In sorting algorithms

Fibonacci Series

Q3. What is stack? Explain push and pop operations of the stack.
In Stack data is arranges in LIFO fashion. LIFO stands for Last-in-first-out. Here,
the element which is placed (inserted or added) last, is accessed first.
Basic features of Stack
1. Stack is an ordered list of similar data type.
2. Stack is a LIFO structure. (Last in First out).
3. 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.
4. 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.

In stack, insertion operation is called PUSH operation and removal operation is


called POP operation.
PUSH OPERATION:

The process of putting a new data element onto stack is known as PUSH
Operation. Push operation involves series of steps

Step 1 Check if stack is full.

Step 2 If stack is full, produce error and exit.

Step 3 If stack is not full, increment top to point next empty space.

Step 4 Add data element to the stack location, where top is pointing.

Step 5 return success.

Algorithm for PUSH operation


A simple algorithm for Push operation can be derived as follows
begin procedure push: stack, data
if stack is full

begin procedure push: stack, data

return null
endif
top top + 1
stack[top] data
end procedure

if stack is full
return null
endif
top top + 1
stack[top] data
end procedure

Pop Operation
Accessing the content while removing it from stack, is known as pop operation.
In array implementation of pop() operation, data element is not actually
removed, instead top is decremented to a lower position in stack to point to
next value. But in linked-list implementation, pop() actually removes data
element and deallocates memory space.
A POP operation may involve the following steps

Step 1 Check if stack is empty.

Step 2 If stack is empty, produce error and exit.

Step 3 If stack is not empty, access the data element at which top is
pointing.

Step 4 Decrease the value of top by 1.

Step 5 return success.

Algorithm for POP operation


A simple algorithm for Pop operation can be derived as follows
begin procedure pop: stack
if stack is empty
return null
endif
data stack[top]
top top - 1
return data
end procedure

Q5. What is polish notation? Define conversion of infix notation into postfix notation.
Definition: Polish notation also known as prefix notation is defined as: In this notation
system operator is written before the operands.
Example of polish notation or prefix notation is +AB or /CD. In these two examples we can
see that here A and B are two operands and + is an operator which is written before
operands.
Conversion of infix notation into postfix notation:

Infix Expression :
Any expression in the standard form like "2*3-4/5" is an Infix(Inorder)
expression.
Postfix Expression :
The Postfix(Postorder) form of the above expression is "23*45/-".
Infix to Postfix Conversion:
In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+.
The algorithm for the conversion is as follows:

Scan the Infix string from left to right.

Initialize an empty stack.

If the scanned character is an operand, add it to the Postfix string. If the scanned character is
an operator and if the stack is empty Push the character to stack.

If the scanned character is an Operand and the stack is not empty, compare the
precedence of the character with the element on top of the stack(topStack).
If topStack has higher precedence over the scanned character Popthe stack
else Push the scanned character to stack. Repeat this step as long as stack is not
empty and topStack has precedence over the character.

Repeat this step till all the characters are scanned.

(After all characters are scanned, we have to add any character that the stackmay have to
the Postfix string.) If stack is not empty add topStack to Postfix string andPop the stack.
Repeat this step as long as stack is not empty.

Return the Postfix string.

Example :
Let us see how the above algorithm will be implemented using an example.
Infix String : a+b*c-d
Initially the Stack is empty and our Postfix string has no characters. Now, the first character scanned
is 'a'. 'a' is added to the Postfix string. The next character scanned is '+'. It being an operator, it is
pushed to the stack.

Postfix String

Stack

Next character scanned is 'b' which will be placed in the Postfix string. Next character is '*' which is
an operator. Now, the top element of the stack is '+' which has lower precedence than '*', so '*' will
be pushed to the stack.

Postfix String

Stack

The next character is 'c' which is placed in the Postfix string. Next character scanned is '-'. The
topmost character in the stack is '*' which has a higher precedence than '-'. Thus '*' will be popped
out from the stack and added to the Postfix string. Even now the stack is not empty. Now the
topmost element of the stack is '+' which has equal priority to '-'. So pop the '+' from the stack and
add it to the Postfix string. The '-' will be pushed to the stack.

Postfix String

Stack

Next character is 'd' which is added to Postfix string. Now all characters have been scanned so we
must pop the remaining elements from the stack and add it to the Postfix string. At this stage we
have only a '-' in the stack. It is popped out and added to the Postfix string. So, after all characters
are scanned, this is how the stack and Postfix string will be :

Postfix String

Stack

End result :
Infix String : a+b*c-d
Postfix String : abc*+d-

Q6.What is a queue? Write Algorithms for the insertion and deletion operations performed on
circular queue.
DEFINITION:
In programming, a queue is a data structure in which elements are removed in the same order they
were entered. This is often referred to as FIFO (first in, first out).

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.
Algorithm for Insertion in a circular queue

1. If (FRONT == 1 and REAR == N) or (FRONT == REAR + 1) Then

2.

Print: Overflow

3. Else

4.

If (REAR == 0) Then [Check if QUEUE is empty]

(a) Set FRONT = 1

(b) Set REAR = 1

5. Else If (REAR == N) Then [If REAR reaches end if QUEUE]

6.

Set REAR = 1

7. Else

8.

Set REAR = REAR + 1 [Increment REAR by 1]

[End of Step 4 If]

9. Set QUEUE[REAR] = ITEM

10. Print: ITEM inserted

[End of Step 1 If]

11. Exit

Algorithm for Deletion in a circular queue:

1. If (FRONT == 0) Then [Check for Underflow]


2.

Print: Underflow

3. Else
4.

ITEM = QUEUE[FRONT]

5.

If (FRONT == REAR) Then [If only element is left]


(a) Set FRONT = 0
(b) Set REAR = 0

6. Else If (FRONT == N) Then [If FRONT reaches end if QUEUE]


7.

Set FRONT = 1

8. Else
9.

Set FRONT = FRONT + 1 [Increment FRONT by 1]


[End of Step 5 If]

10. Print: ITEM deleted


[End of Step 1 If]
11. Exit
Q7.What is algorithm? Define the complexity of algorithms. Also define the time complexity of
merge sort.
Definition of algorithm: Algorithm is a step by step process to get the
solution for a well-defined problem.
Properties of an algorithm:
- Should be written in simple English
- Should be unambiguous, precise and lucid
- Should provide the correct solutions
- Should have an end point
- The output statements should follow input, process instructions

- The initial statements should be of input statements


- Should have finite number of steps
- Every statement should be definitive
Complexity of Algorithms: The complexity of an algorithm is a function
describing the efficiency of the algorithm in terms of the amount of data the
algorithm must process.
Time complexity of merge-sort: Merge sort is a divide and conquer algorithm,
as outlined below. the function mergesort calls itself recursively.
list mergesort (list L, int n);
{
if (n = = 1)
return (L)
else {
Split L into two halves L1 and L2 ;

return (merge (mergesort (L1,

), (mergesort (L2,

))

}
}
Let T(n) be the running time of Mergesort on an input list of size n. Then,
T(n)

C1 (if n = 1)

(C1 is a constant)

(if n > 1)

If n = 2k for some k, it can be shown that

T(n)

2kT(1) + C2k2k

That is, T(n) is O(nlog n).

Q8.What is binary tree? Define the terminologies of binary tree.


Definition: Binary Tree is a special data structure used for data storage purposes.
A binary tree has a special condition that each node can have two children at
maximum. A binary tree have benefits of both an ordered array and a linked list as
search is as quick as in sorted array and insertion or deletion operation are as fast
as in linked list.

Terminologies of binary tree:


Following are important terms with respect to tree.

Path Path refers to sequence of nodes along the edges of a tree.

Root Node at the top of the tree is called root. There is only one root
per tree and one path from root node to any node.

Parent Any node except root node has one edge upward to a node
called parent.

Child Node below a given node connected by its edge downward is


called its child node.

Leaf Node which does not have any child node is called leaf node.

Subtree Subtree represents descendents of a node.

Visiting Visiting refers to checking value of a node when control is on


the node.

Traversing Traversing means passing through nodes in a specific


order.

Levels Level of a node represents the generation of a node. If root


node is at level 0, then its next child node is at level 1, its grandchild is at
level 2 and so on.

keys Key represents a value of a node based on which a search


operation is to be carried out for a node.

Q8. Explain the pre-order, in-order and post-order traversal of binary tree.
Traversal is a process to visit all the nodes of a tree and may print their values
too. Because, all nodes are connected via edges (links) we always start from
the root (head) node.
Inorder traversal: In this traversal
method, the left left-subtree is visited first, then root and then the right subtree. We should always remember that every node may represent a subtree
itself.If a binary tree is traversed inorder, the output will produce sorted key
values in ascending order.

We start from A, and following in-order traversal, we move to its left


subtree B.B is also traversed in-ordered. And the process goes on until all the
nodes are visited. The output of in-order traversal of this tree will be
DBEAFCG
Algorithm:
Until all nodes are traversed
Step 1 Recursively traverse left subtree.
Step 2 Visit root node.
Step 3 Recursively traverse right subtree.
Pre-order Traversal:
In this traversal method, the root node is visited first, then left subtree and finally right sub-tree.

We start from A, and following pre-order traversal, we first visit A itself and
then move to its left subtree B. B is also traversed pre-ordered. And the
process goes on until all the nodes are visited. The output of pre-order traversal
of this tree will be
ABDECFG
Algorithm
Until all nodes are traversed
Step 1 Visit root node.
Step 2 Recursively traverse left subtree.
Step 3 Recursively traverse right subtree.
PostOrder Traversal:
In this traversal method, the root node is visited last. First we traverse left
subtree, then right subtree and finally root.

We start from A, and following pre-order traversal, we first visit left


subtree B.B is also traversed post-ordered. And the process goes on until all
the nodes are visited. The output of post-order traversal of this tree will be
DEBFGCA
Algorithm
Until all nodes are traversed
Step 1 Recursively traverse left subtree.
Step 2 Recursively traverse right subtree.
Step 3 Visit root node.
Q. What is AVL tree? Explain with suitable example.
AVL tree is named after their inventor Adelson, Velski & Landis, AVL trees are
height balancing binary search tree. AVL tree checks the height of left and right
sub-trees and assures that the difference is not more than 1. This difference is
called Balance Factor.
BalanceFactor = height(left-sutree) height(right-sutree)
If the difference in the height of left and right sub-trees is more than 1, the tree
is balanced using some rotation techniques.
There are four kinds of rotations

Left rotation

Right rotation

Left-Right rotation

Right-Left rotation

example of AVL trees is the behavior on a worst-case add sequence for regular
binary trees:
1, 2, 3, 4, 5, 6, 7
All insertions are right-right and so rotations are all single rotate from
the right. All but two insertions require re-balancing:

As depicted, the unbalanced node becomes right child of its left child by
performing a right rotation.
Q. What is B-tree? Explain algorithm of b-tree in order.
Definition: A B-tree is a tree data structure that keeps data sorted and allows
searches, insertions, and deletions in logarithmic amortized time. Unlike selfbalancing 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.
Important properties of a B-tree:

B-tree nodes have many more than two children.

A B-tree node may contain more than just a single element.

Algorithm for Searching a B-tree:


function Search (ROOT_RRN, KEY, NODE_RRN, NODE_POS)

(* In this algorithm
Found :

a flag to indicate if the record has been found

key of record being searched for

holds a pointer to a node

Ri

record i in current node

*)

Found = false
read root at location ROOT_RRN
P = ROOT_RRN
repeat
N = number of records in current node
case
KEY = key of record in current node (set i): found = true
KEY < key(R1)
KEY > key(RN)
Otherwise
< KEY < key(Ri))
endcase
if P not null then
read node pointed to by P
endif
until Found or P is null

if Found then
NODE_POS = i
NODE_RRN = P
endif
Search = Found

P = P0

P = PN
:

P = Pi1 (for some i where key(Ri1)

return
Insertion
1) Initialize x as root.
2) While x is not leaf, do following
..a) Find the child of x that is going to to be traversed next. Let the child be y.
..b) If y is not full, change x to point to y.
..c) If y is full, split it and change x to point to one of the two parts of y. If k is
smaller than mid key in y, then set x as first part of y. Else second part of y.
When we split y, we move a key from y to its parent x.
3) The loop in step 2 stops when x is leaf. x must have space for 1 extra key as
we have been splitting all nodes in advance. So simply insert k to x.
Deletion

function delete(ROOT_RRN, Out-rec)

(* In this algorithm
Finished

TWOBNODE :
normal node
A-sibling
Out-rec

a flag that indicates if deletion has finished


an oversize node that is about 50% larger than a

an adjacent sibling node


:

the record to be deleted from the tree

*)

(* Search tree for In-rec forming stack of node addresses *)


Found = false
read root at ROOT_RRN
repeat
N = number of records in current node

case
key(Out-rec) = key of record in current node: found = true
key(Out-rec) < key(R1)

: P = P0

key(Out-rec) > key(RN)

: P = PN

Otherwise
1) < KEY < key(Ri))

: P = Pi1 (for some i where key(Ri

endcase
if P not null then
push onto stack address of current node
read node pointed to by P
endif
until Found or P is null

if not Found then


delete = false
return
endif

if Out-rec is not in terminal node then


Search for successor record of Out-rec at terminal level (stacking node
addresses)
Copy successor over Out-rec
Terminal node successor now becomes the Out-rec
endif

(* remove record and adjust tree *)

Finished = false
repeat
Remove Out-rec (record Ri) and pointer Pi
if current node is root or is not too small then
Finished = true
else
if redistribution possible then (* an A-sibling > minimum *)
(* redistribute *)
copy best A-sibling, intermediate parent record, and current (too-small) node
into TWOBNODE
copy records and pointers from TWOBNODE to best A-sibling, parent, and
current node so A-sibling and current node are roughly equal size
Finished = true
else

(* concatenate with appropriate A-sibling *)


Choose best A-sibling to concatenate with

Put in the leftmost of the current node and A-sibling the contents of both nodes
and the intermediate record from the parent
Discard rightmost of the two nodes
Intermediate record in parent now becomes Out-rec
until Finished

if no records in root then (* tree shrinks *)


new root is the node pointed to by the current root
discard old root
endif
delete = true
return
Q. What is graph? Explain types and terminologies of graph.

Ggraph is a pictorial representation of a set of objects where some pairs of


objects are connected by links. The interconnected objects are represented by
points termed as vertices, and the links that connect the vertices are called
edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is
the set of edges, connecting the pairs of vertices. Take a look at the following
graph

In the above graph,


V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}
Graph Data Structure
Mathematical graphs can be represented in data-structure.
Terminologies of graph:
Vertex each node of the graph is represented as a vertex. In example given
below, labeled circle represents vertices. So A to G are vertices. We can
represent them using an array as shown in image below. Here A can be
identified by index 0. B can be identified using index 1 and so on.

Edge Edge represents a path between two vertices or a line between


two vertices. In example given below, lines from A to B, B to C and so on
represents edges. We can use a two dimensional array to represent array
as shown in image below. Here AB can be represented as 1 at row 0,
column 1, BC as 1 at row 1, column 2 and so on, keeping other
combinations as 0.

Adjacency Two node or vertices are adjacent if they are connected to


each other through an edge. In example given below, B is adjacent to A,
C is adjacent to B and so on.

Path Path represents a sequence of edges between two vertices. In


example given below, ABCD represents a path from A to D.

Following are basic primary operations of a Graph which are following.

Add Vertex add a vertex to a graph.

Add Edge add an edge between two vertices of a graph.

Display Vertex display a vertex of a graph.

Q. write short notes on the following.


1. Binary Search
2. Insertion and Selection sorting
3. Hash Table
4. Collision resolution technique.
5. Dynamic memory allocation.
BINARY SEARCH:
Binary search is a fast search algorithm with run-time complexity of (log n). This search
algorithm works on the principle of divide and conquer. For this algorithm to work properly the data
collection should be in sorted form.
The below given is our sorted array and assume that we need to search location of value 31 using
binary search.

First, we shall determine the half of the array by using this formula

mid = low + (high - low) / 2


Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So 4 is the mid of array.

Now we compare the value stored at location 4, with the value being searched i.e. 31. We find that
value at location 4 is 27, which is not a match. Because value is greater than 27 and we have a
sorted array so we also know that target value must be in upper portion of the array.

We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.

The value stored at location 7 is not a match, rather it is less that what we are looking for. So the
value must be in lower part from this location.

So we calculate the mid again. This time it is 5.

We compare the value stored ad location 5 with our target value. We find that it is a match.

We conclude that the target value 31 is stored at location 5.


Binary search halves the searchable items and thus reduces the count of comparisons to be made to
very less numbers.

INSERTION AND SELECTION SORTING:


Insertion sort: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list)
one item at a time.
take an unsorted array for our example.

Insertion sort compares the first two elements.

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in correct position.

It swaps 33 with 27. Also it checks with all the elements of sorted sublist. Here we see that sorted
sub-list has only one element 14 and 27 is greater than 14. Hence sorted sub-list remain sorted after
swapping.

By now we have 14 and 27 in the sorted sublist. Next it compares 33 with 10,.

These values are not in sorted order.

So we swap them.

But swapping makes 27 and 10 unsorted.

So we swap them too.

Again we find 14 and 10 in unsorted order.

And we swap them. By the end of third iteration we have a sorted sublist of 4 items.

This process goes until all the unsorted values are covered in sorted sublist. And now we shall see
some programming aspects of insertion sort.
Algorithm
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:
The selection sort is a combination of searching and sorting. During each pass, the unsorted element
with the smallest (or largest) value is moved to its proper position in the array. The number of times
the sort passes through the array is one less than the number of items in the array.
take the below depicted array for our example.

For the first position in the sorted list, the whole list is scanned sequentially. The first position
where 14 is stored presently, we search the whole list and find that 10 is the lowest value.

So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list,
appears in the first position of sorted list.

For the second position, where 33 is residing, we start scanning the rest of the list in linear manner.

We find that 14 is the second lowest value in the list and it should appear at the second place. We
swap these values.

After two iterations, two least values are positioned at the the beginning in the sorted manner.

The same process is applied on the rest of the items in the array
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
Hash table: Hash Table is a data structure which store data in associative manner. In hash table,
data is stored in array format where each data values has its own unique index value.
Basic Operations
Following are basic primary operations of a hashtable which are following.

Search search an element in a hashtable.

Insert insert an element in a hashtable.

delete delete an element from a hashtable.

// read from book please


COLLISION RESOLUTION TECHNIQUE:
Read from book.

DYNAMIC MEMORY ALLOCATION:

Read from book. No proper data available on this topic.

YEAR 2010
Q. What do you mean by abstract data structure.

Definition: A data type can be considered abstract when it is defined in terms of operations on it,
and its implementation is hidden.An Abstract Data Type is an organized collection of information
and a set of operations used to manage that information. The set of operations defines the interface
of the ADT. As long as the ADT fulfills the conditions of the interface, it doesnt really matter how
the ADT is implemented. Since, in ADT, the data values and operations are defined with
mathematical precision, rather than as an implementation in a computer language, we may reason
about effects of the operations, relations to other abstract data types whether a program implements
the data type etc. One of the simplest abstract data type is the stack data type for which functions
might be provided to create an empty stack, to push values onto a stack and to pop values from a
stack.
An Abstract Data Type is a data type that satisfies the following two conditions:
1. The representation, or definition, of the type and the operations are contained in a single
syntactic unit.
2. The representation of objects of the type is hidden from the program units that use the type,
so only direct operations possible on those objects are those provided in the types
definition.
A user defined Abstract Data Type should provide:
1. A type definition that allows program units to declare variables of the type, but hides the
representation of these variables.
2. A set of operations for manipulating objects of the type.
An example of a user defined abstract data type is structure. C provides four basic types: int, char,
float and double. However, C also provides the programmer with the ability to define his/her own
types. Structure is one such example. A structure is an aggregate of different parts, where each part
is of some existing type.
struct abc

{int x;

float y;

};
Q2 What is stack? Explain primitive operation which can be performed on stack.
Already answered. PUSH AND POP also primitive operations.
Q3. What is queue? Discuss circular queue and priority queue in data structure.

Circular queue: Circular queue is a linear data structure. It follows FIFO principle.

In circular queue the last node is connected back to the first node to make a circle.

Circular linked list fallow the First In First Out principle

Elements are added at the rear end and the elements are deleted at front end of the queue

Both the front and the rear pointers points to the beginning of the array.

It

is also called as Ring buffer.

Circular Queue can be created in three ways they are


Using single linked list
Using double linked list
Using arrays
Using single linked list:
It is an extension for the basic single linked list. In circular linked list Instead of storing a Null value in the last
node of a single linked list, store the address of the 1st node (root) forms a circular linked list.
The following figure shows circular single linked list:

Using double linked list


In double linked list the right side pointer points to the next node address or the address of first node and left
side pointer points to the previous node address or the address of last node of a list. The following figure
shows Circular Double linked list :-

Priority Queue is more specialized data structure than Queue. Like ordinary queue, priority queue
has same method but with a major difference. In Priority queue items are ordered by key value so
that item with the lowest value of key is at front and item with the highest value of key is at rear or
vice versa. So we're assigned priority to item based on its key value. Lower the value, higher the
priority.

Basic Operations

insert / enqueue add an item to the rear of the queue.

remove / dequeue remove an item from the front of the queue.

Insert / Enqueue Operation

Whenever an element is inserted into queue, priority queue inserts the


item according to its order. Here we're assuming that data with high
value has low priority.

Remove / Dequeue Operation


Whenever an element is to be removed from queue, queue get the element using item count. Once
element is removed. Item count is reduced by one.

Q. What do you mean by linked list of stack and linked list pf queue.? explain doubly and circular
linked list.
Linked-List Implementation of Stacks
a stack uses a linked list, which is a data structure that links together individual data objects as if
they were ``links'' in a ``chain'' of data.
Here is a sketch of a linked-list-based ``stack'' that holds 1, then 5, and then 20 at the bottom:
--top ---> | 1 |

|---|

---

| o-|---> | 5 |
---

|---|

----

| o-|---> | 20 |
---

|----|
|null|
----

The list consists of three ``cells,'' each of which holds a data object and a ``link'' to another cell. A
variable, top, holds the address of the first cell in the list. An empty stack looks like this:
top ---> null
(That is, variable top holds value, null.) Each time an object is pushed, a cell is constructed, the
object is inserted into the cell, and the cell is linked to the front of the chain of cells. For example,
pushing 20onto the empty stack gives us
---top ---> | 20 |
|--- |
|null|
---After 5 and then 1 are pushed, we obtain the picture first seen.
Say that we pop an object from the stack; the picture changes to this:
--top ---> | 5 |
|---|

----

| o-|---> | 20 |
---

|----|
|null|
----

Doubly Linked List: Doubly Linked List is a variation of Linked list in which navigation is possible
in both ways either forward and backward easily as compared to Single Linked List. Following are
important terms to understand the concepts of doubly Linked List

Link Each Link of a linked list can store a data called an element.

Next Each Link of a linked list contain a link to next link called Next.

Prev Each Link of a linked list contain a link to previous link called Prev.

LinkedList A LinkedList contains the connection link to the first Link called First and to
the last link called Last.

Doubly Linked List Representation

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

Doubly LinkedList contains an link element called first and last.

Each Link carries a data field(s) and a Link Field called next.

Each Link is linked with its next link using its next link.

Each Link is linked with its previous link using its prev link.

Last Link carries a Link as null to mark the end of the list.

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

Insertion add an element at the beginning of the list.

Deletion delete an element at the beginning of the list.

Insert Last add an element in the end of the list.

Delete Last delete an element from the end of the list.

Insert After add an element after an item of the list.

Delete delete an element from the list using key.

Display forward displaying complete list in forward manner.

Display backward displaying complete list in backward manner.

Circular linked is explained already.


Q. Application of binary-tree and threaded binary tree.

Applications of binary trees

Binary Search Tree - Used in many search applications where data is


constantly entering/leaving, such as the map and set objects in many
languages' libraries.

Binary Space Partition - Used in almost every 3D video game to determine


what objects need to be rendered.

Binary Tries - Used in almost every high-bandwidth router for storing routertables.

Hash Trees - used in p2p programs and specialized image-signatures in


which a hash needs to be verified, but the whole file is not available.

Heaps - Used in implementing efficient priority-queues, which in turn are


used for scheduling processes in many operating systems, Quality-of-Service in
routers, and A* (path-finding algorithm used in AI applications, including
robotics and video games). Also used in heap-sort.

Huffman Coding Tree (Chip Uni) - used in compression algorithms, such as


those used by the .jpeg and .mp3 file-formats.

GGM Trees - Used in cryptographic applications to generate a tree of pseudorandom numbers.

Syntax Tree - Constructed by compilers and (implicitly) calculators to parse


expressions.

Treap - Randomized data structure used in wireless networking and memory


allocation.

T-tree - Though most databases use some form of B-tree to store data on the
drive, databases which keep all (most) their data in memory often use T-trees
to do so.

Q. Explain sequential seaarch, binary search, insertion sort and quick sort.
SEQUENTIAL SEARCH: When data items are stored in a collection such as a list, each data item is
stored in a position relative to the others. Since these index values are ordered, it is possible for us to
visit them in sequence. This process gives rise searching technique, the sequential search.

Algorithm: Sequential Search ( Array A, Value x)

Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
QUICK SORT: Quick sort is not stable search, but it is very fast and requires very less additional
space. It is based on the rule of Divide and Conquer(also called partition-exchange sort). This
algorithm divides the list into three main parts :
1. Elements less than the Pivot element
2. Pivot element
3. Elements greater than the pivot element
In the list of elements, mentioned in below example, we have taken 25 as pivot. So after the first
pass, the list will be changed like this.
6 8 17 14 25 63 37 52

Hence after the first pass, pivot will be set at its position, with all the elements smaller to it on its
left and all the elements larger than it on the right. Now 6 8 17 14 and 63 37 52 are considered as
two separate lists, and same logic is applied on them, and we keep doing this until the complete list
is sorted.

Q What do you mean by directed and undirected and weighted graph. Also discuss representation of
graphs.

Undirected Graphs.

In an undirected graph, the order of the vertices in the pairs in the Edge set doesn't matter. Thus, if
we view the sample graph above we could have written the Edge set as {(4,6),(4,5),(3,4),(3,2),
(2,5)),(1,2)),(1,5)}. Undirected graphs usually are drawn with straight lines between the vertices.
The adjacency relation is symetric in an undirected graph.
Directed Graphs.
In a directed graph the order of the vertices in the pairs in the edge set matters. Thus u is adjacent to
v only if the pair (u,v) is in the Edge set. For directed graphs we usually use arrows for the arcs
between vertices. An arrow from u to v is drawn only if (u,v) is in the Edge set. The directed graph
below

Has the following parts.


o

The underlying set for the Verticies set is capital letters.

The Vertices set = {A,B,C,D,E}

The Edge set = {(A,B),(B,C),(D,C),(B,D),(D,B),(E,D),(B,E)}

Note that both (B,D) and (D,B) are in the Edge set, so the arc between B and D is an arrow in both
directions.
Weighted Graphs.
A weighted graph is an edge labeled graph where the labels can be operated on by the usual
arithmetic operators, including comparisons like using less than and greater than. the weights are
drawn adjacent to the edges and appear in dark purple.

Here we have the following parts.

The underlying set for the the Vertices set is Integer.

The underlying set for the weights is Integer.

The Vertices set = {1,2,3,4,5}

The Edge set = {(1,4,5) ,(4,5,58) ,(3,5,34) ,(2,4,5) ,(2,5,4) ,(3,2,14) ,(1,2,2)}

Representation of graphs is already answered.


Q. Write sort notes on:
1. Bubble sort
2. Comparison of sorting method.
3. Representation of graph.
4. Analysis of algorithm.
BUBBLE SORT: Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison
based algorithm in which each pair of adjacent elements is compared and elements are swapped if
they are not in order. We take an unsorted array for our example. Bubble sort take (n2) time so
we're keeping short and precise.

Bubble sort starts with very first two elements, comparing them to check which one is greater.

In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33
with 27.

We find that 27 is smaller than 33 and these two values must be swapped.

The new array should look like this

Next we compare 33 and 35. We find that both are in already sorted positions.

Then we move to next two values, 35 and 10.

We know than 10 is smaller 35. Hence they are not sorted.

We swap these values. We find that we reach at the end of the array. After one iteration the array
should look like this

To be precise, we are now showing that how array should look like after each iteration. After second
iteration, it should look like this

Notice that after each iteration, at least one value moves at the end.

And when there's no swap required, bubble sorts learns that array is completely sorted.

Now we should look into some practical aspects of bubble sort.


ALGORITHM:
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

Comparison of sorting algorithms: Use your book.

Analysis of algorithm: Already answered. In question number 7 in 2014.


YEAR 2011
Write Sort notes on:

Redix sort: Radix Sort is a clever and intuitive little sorting algorithm. Radix Sort puts the elements in
order by comparing the digits of the numbers.

Example:
let this is original, unsorted list:
170, 45, 75, 90, 802, 24, 2, 66
Sorting by least significant digit (1s place) gives:
170, 90, 802, 2, 24, 45, 75, 66
Sorting by next digit (10s place) gives: [*Notice that 802 again comes before 2 as 802 comes before 2 in the
previous list.]
802, 2, 24, 45, 66, 170, 75, 90
Sorting by most significant digit (100s place) gives:
2, 24, 45, 66, 75, 90, 170, 802

You might also like