Screenshot 2024-10-06 at 9.02.46 PM
Screenshot 2024-10-06 at 9.02.46 PM
Compiled by
Faculty
DATA STRUCTURES USING C++ QUESTION BANK
Weightage Table
Blueprint
2. The Sequence of the Instruction written to perform a specific task is called the .
A. Statement
B. Program
C. Algorithm
D. None of the above
10. This Loop tests the condition after having executed the Statements within the Loop.
A. while
B. do-while
C. for Loop
D. if-else-if
11. To implement sparse matrix dynamically, the following data structure is used
A. Trees
B. Graphs
C. Priority Queues
D. Linked List
13. The optimal data structure used to solve the Towers of Hanoi is
A. Tree
B. Heap
C. Priority queue
D. Stack
14. What is the number of moves required to solve Tower of Hanoi problem for k disks?
A. 2k – 1
B. 2k + 1
C. 2k + 1
D. 2k – 1
15. Which of the following data structure can't store the non-homogeneous data elements?
A. Arrays
B. Records
C.Pointers
D.None
21. Which Data Structure is mainly used for implementing the recursive algorithm?
A. Queue
B. Stack
C. Linked List
D. Tree
With an ADT, we know what a specify data type can do, but how it actually does it is hidden. ADT consists
of a set of definitions that allow us to use the functions while hiding the implementation. Weencapsulate the
data and the operations on data and then we hide them from the user.
Note that MEAN is the name of the sub algorithm and A, B and C are the parameters. The return
statement includes the variable AVE whose value is returned to the callingprogram.
Data structures are generally classified into primitive and non-primitive data structures.
Single alternative
This structure has the form
If condition then,[Module
A][End of if structure]
Here, the if condition holds, then module A which consists of one or more statements is executed;
otherwise Module A is skipped and control transfers to the next step of the algorithm.
Double alternative
This structure has the form If condition, then:
[Module A]
Else
[Module B]
[End of if structure]
The logic of this structure is picture in fig. 2-4(b). As indicated by the flowchart, if the condition
holds, then module A is executed; otherwise Module B is executed.
Multiple alternative
This structure has the form:
If condition(1), then:
[Module A1]
Else if condition(2), then:
[Module A2]
.
.
.
Else if condition (M), then:
[Module AM] Else:
[Module B]
[End of if structure]
The logic of this structure allows only one of the modules to be executed. Specifically, either
the module which follows the first condition which holds is executed, or the module which
follows thefinal Else statement is executed. In practice, there will rarely be more than three
alternatives.
The repeat-for loop uses an index variable, such as K to control the loop. The loop will usually
have the form:
Repeat for k=R to S by T:
[Module]
[End of loop]
The repeat-while loop uses a condition to control the loop. The loop will usually have the form
Repeat while condition:
[module]
[end of
loop]
The looping continues until the condition is false
3. What do you mean by a recursion? Give any 2 recursive techniques.
Recursion is the name given to the technique of defining a set or a process in terms of itself. A
recursive procedure can be called from within or outside itself.
Suppose P is a procedure containing either a call statement to itself or a call statement to asecond
procedure that may eventually result in a call statement back to the original procedure P. then P is
called a recursive procedure.
1. There must be certain criteria, called base criteria, for which the procedure does not call itself.
2. Each time a procedure calls itself, it must be closer to the base criteria.
The product of positive integers from 1 to n, is called” n factorial” and is usually denoted
by n!N! =1 2 3 ..(N-1) N
a) If n=0, then n! =1
b) If n>0, the n! =n.(n-1)!
Observe that the definition of n! is recursive, since it refers to itself when it uses (n-1)!However
1. The value of n! is explicitly given when n=0 (thus 0 is the base value)
2. The value of n! for arbitrary n is defined in terms of a smaller value of n which is closer to
the base value 0 accordingly, this definition is not circular. And is well defined.
The following procedures calculate n factorial.
This procedure calculates n! and returns the value in the variable Fact.
1. If n=0 then
2. Set Fact: =1 and return
3. Call Factorial (Fact, n-1)
4. Set Fact: =n*Fact(n-1)
5. Return
5. Explain Fibonacci series by using recursive technique.
This is another example of a recursive definition, since the definition refers toitself
when it uses Fn-2 and Fn-1. Here
a) The base values are 0 and 1
b) The value of Fn is defined in terms of smaller values of n which are closer to
the basevalues. Accordingly, this function is well defined.
A procedure for finding the nth term Fn of the Fibonacci sequence follows:
This procedure calculates Fn and returns the value in the first parameter Fib.
The Tower of Hanoi is a mathematical puzzle invented by the French mathematician Eduard
Lucas in 1883.
There are three pegs, source(A), Auxiliary (B), and Destination(C). Peg A containsa set of disks
stacked to resemble a tower, with the largest disk at the bottom and the smallest disk at the top.
figure 1 Illustrate the initial configuration of the pegs for 3disks. The objective is to transfer the
entire tower of disks in peg A to peg C maintaining the same order as the disks.
Rules:
Algorithm:
1. Full form of access is used to add and remove nodes from a queue.
A.LIFO
B.FIFO
C.Both a and b
D.None of these
2. In the linked representation of the stack behaves as the top pointer variable of the stack.
A. Stop pointer
B. Begin pointer
C. Start pointer
D. Avail pointer
4. In the linked representation of the stack the null pointer of the last node in the list indicates
A. Beginning of the stack
B. Bottom of the stack
C. Middle of the stack
D. In between some value
13. _________is the term used to delete an element from the stack.
A. Push
B. Pull
C. Pop
D. Pump
15. A pointer variable that contains the location at the top element of the stack is called
A. Top
B. Last
C. Final
D. End
18. A data structure in which elements can be inserted or deleted at/from both ends but
not in the middle is?
A. Queue
B. Circular queue
C. Dequeue
D. Priority Queue
19. In the linked representations of the stack holds the elements of the stack.
A. INFO fields
B. TOP fields
C. LINK fields
D. NULL fields
25. If the elements “A”,” B”,”C” and “D” are placed in a queue and are deleted one at a time, in what order
will they be removed?
A. ABCD
B. DCBA
C. DCAB
D. ABDC
Algorithm:
o Two pointer variables FRONT and REAR pointing to the nodes which is in the front and rear of the
queue.
o The INFO field of the node holds the data in the queue.
o The NEXT is the pointer to the next element in the queue.
1. N= new node
2. If (n==NULL)
3. Then write (“Overflow”) and exit
4. N->info=ITEM
5. If (Front==NULL) then
6. Front=Rear=n
7. Else
8. Rear->next=n
9. Rear=n
10. N->next=NULL
11. finished
80 (head) 100 120 140
140 160
Procedure LQDELETE( INFO, NEXT,FRONT, REAR, ITEM,TEMP)
This procedure deletes the front element of the linked queue and stores it in ITEM.
1. Temp= front
2. Item=front->info
3. Front=temp->next
4. Delete temp
5. Finished
AFTER DELETION:
Priority queue: This is a collection of elements such that each element has been assigned a priority and
such that the order in which elements are deleted and processed takes place. An element of higher
priority is processed before any element of lower priority. Two elements with the same priority are
processed according to the order in which they were added to the queue.
Dequeue: Double-ended queue in which elements can be added or removed at either end but not in the
middle. Two variations:-
1) Input restricted deque: An input-restricted deque is a deque that allows insertions at only one end of
the listbut allows deletions at both ends of the list.
2) Output restricted deque: An output-restricted deque is a deque that allows deletions at only one end
of the list butallows insertions at both ends of the list.
PROCEDURE CQINSERT(F,R,Q,N,Y): Given F and R as the pointers to the front and rear element of a
circular queue. The array Q contains N elements. Y is the element to be inserted at the rear.
Step 1: IF (REAR+1)%MAX = FRONT
Write " OVERFLOW "
Goto step 4
[End OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
Write " OVERFLOW "
ELSE IF REAR = MAX - 1 and FRONT! = 0
SET REAR = 0
ELSE
SET REAR = (REAR + 1) % MAX
[END OF IF]
Step 3: SET QUEUE[REAR] = VAL
Step 4: EXIT
FUNCTION CQDELETE(F,R,Q,N): Given F and R as the pointers to the front and rear
element of a circular queue. The array Q contains N elements. This function deletes and
returns the last element of the queue. Y is the temporary variable.
Step 1: IF FRONT = -1
Write " UNDERFLOW "
Goto Step 4
Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = (FRONT + 1)%N
[END of IF]
[END OF IF]
Step 4: EXIT
2. Evaluate ABC*+D- with proper step. Assume A=4, B=6, C=2, D=4.
ABC*+D-
462*+4-
Step Input Symbol/Element Stack Intermediate Output
1 4 Push 4
2 6 Push 46
3 2 Push 462
4 12
4 * Pop 2 elements and evaluate
4 12 16
5 Push result 12
6 + Pop 2 elements and evaluate 16
7 Push result 16 16 4 12
8 4 Push
9 - Pop 2 elements and evaluate 12 12
10 Push result 12
11 No more elements
OR
This procedure converts an infix expression to postfix expression. The infix expression is taken in
inputExpr, st represents a new stack, Symbol is the current Symbol, stack_top_symbol is the symbol at the
top of the stack, topSymbol is/are the symbol(s) remained in the stack at the end of the evaluation and
outputExpr is the postfix expression
/*to pop the remaining operators from the stack at the end.*/
topSymbol=st.pop()
add topSymbol to outputExpr
end while
This procedure evaluates an postfixexpression. Expression is the postfix expression. st represents a new
stack, Symbol is the current symbol
St=new stack
Repeat for every character in the expression
Begin
Symbol=current character in the expression
If(symbol is an operand)
St.push(symbol)
END
Else
Begin
Operand2=st.pop()
Operand1=st.pop()
Answer=operand2 and operand1 operated with symbol
St.push(answer)
END
Return st.pop()//display the output
5. Write the PUSH and POP operations in a stack.
PROCEDURE PUSH(S, TOP, X)
This procedure inserts an element X into the top of the stack which is represented byan array S. The array
S contains N elements with a pointer TOP denoting the top element inthe stack.
1. [Check for Overflow]
If TOP>=N
Then write (“OVERFLOW”)
Return
2. [Increment TOP]
TOP=TOP+1
3. [Insert Element]
S[TOP]=X
4. [Finished]
Return
FUNCTION POP(S,TOP):
This function removes the top element from a stack which is represented by a vector Sand returns this
element. TOP is a pointer to the top element of the stack.
Exit
2.[Decrement TOP pointer]TOP=TOP-1
3.[Return former top element of the Stack]Return
(S[TOP+1])
231*+9–
9. In a linked list the field contains the address of the next element in the list.
A. Link field
B. Next element field
C. Start field
D. Info field
13.A linear list in which the pointer points only to the successive node is
A. singly linked list
B. circular linked list
C. doubly linked list
D. none of the above
14.A linear list in which the last node points to the first node is
A. singly linked list
B. circular linked list
C. doubly linked list
D. none of the above
21. Which header file should be included to use functions like malloc() and calloc()?
A. dos.h
B. string.h
C. stdlib.h
D. memory.h
24. Indexing the element in the list is not possible in linked lists.
A. middle
B. first
C. last
D. anywhere in between
25. may take place only when there is some minimum amount (or) no
space left in free storage list.
A. Memory management
B. Garbage collection
C. Recycle bin
D. Memory management
1. What do you mean by linked list? With a neat diagram explain different types of linkedlists.
A linked list is a non-sequential collection of data items. For every data item in the linked list, there is an
associated pointer that gives the memory location of the next data item in the linked list. The data items in
the linked list are not in a consecutive memory locations. But they may be anywhere in memory. However,
accessing of these items is easier as each data itemcontained within itself the address of the next data item.
2. Write an algorithm to insert nodes from the beginning and end, of a singly linked list.
• Algorithm for inserting a node at the beginning of a linked list
Procedure Insert_Head(n)
This algorithm inserts a new node called n to the beginning of a linked list. Head denote the starting node
of the linked list.
1. [make head as the next element to the newnode]
N->next=head
2. [make our new node as head]
Head=n
3. [finished]
Exit
Procedure insert_middle(n)
This algorithm inserts a new node called n in the specified position of the linked list.
After is a node where the new node is to be inserted after it.
1. N next=after next
2. After next =n
3. Exit
OR
1. Newnode=n
3.temp next=newnode
4.Exit
5. Write an algorithm to insert nodes from the beginning, end of a circular linked list.
(Questions for Application)
Syntax:
ptr = (cast-type*) malloc(byte-size);
For Example:
ptr = (int*) malloc(100 * sizeof(int));
❖ calloc():- Allocate space for an array of elements, initialize them to zero and
returns a pointer to the first byte of allocated space.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
Here, n is the no. of elements and element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
❖ free():- Free the previously allocated space.
Syntax:
free(ptr);
2. Write an algorithm to traverse a linked list.
Let LIST be a linked list in memory. This algorithm traverses LIST, applying an operation DISPLAY to each
element of LIST. The variable TEMP points to the node which is currently being processed.
1. Set Temp=head
2. While(temp!=NULL)
3. Begin
4. Display temp→info
5. Set temp=temp→next
6. End
7. Finished
3. Write an algorithm to delete nodes from the beginning and end of a singly linked list.
• Algorithm for deleting the last node form the linked list
Procedure Delete_Head ()
This algorithm deletes the head node of the linked list. Temp is a temporary variablewhere the head node
is stored temporarily before deletion takes place.
1. temp=head
2. Head=head→next
3. Delete temp
4. Exit
• Algorithm for deleting the last node form the linked list
Procedure delete_end()
This algorithm deletes the last node of the linked list. Temp is a temporary variablewhere the head node
is stored temporarily before deletion process takes place.
1. Temp=head
2. While(temp->next->next!=NULL)
3. Begin
4. Temp=temp->next
5. End
6. Delete temp->next
7. Temp->next=NULL
8. Exit
OR
1. Temp=head
2. While(temp->next!=NULL)
Begin
3. Previousnode=temp
4. Temp=temp->next
End
5. Previousnode->next=NULL
6. Delete Temp
4. Write an algorithm to delete nodes from the specified position(middle) of a singly linked list.
Procedure Delete_middle(n)
This algorithm deletes a node from the middle of the linked list. Temp is a temporary variable
where the node is stored temporarily before deletion takes place. After is a node where the
node to be deleted after that.
1. Temp=after→next
2. After→next=after→next→next
3. Delete temp
4. Exit
OR
1. nextnode=temp->next
2. temp->next=nextnode ->next
3. Delete nextnode
4. Exit
6. Write an algorithm to delete nodes from the end of a circular linked list.
Procedure delete_end()
1. Temp=head
2. while(temp->next!=HEAD)
Begin
3. Previousnode=temp
4. Temp=temp->next
End
5. Previousnode->next=HEAD
6. Delete Temp
OR
1. temp=head
2. while(temp →next→next!=head)
begin
3. temp=temp→next
end
MODULE 4
Multiple Choice Questions
(Questions for Understanding)
1. The number of edges from the node to the deepest leaf is called of the tree.
A. Height
B. Depth
C. Length
D. Width
3. What will be the height of a balanced full binary tree with 8 leaves?
A. 8
B. 5
C. 6
D. 4
5. Trees are said if they are similar and have same contents at corresponding nodes.
A. Duplicate
B. Carbon copy
C. Replica
D. Copies
6. Every node N in a binary tree T except the root has a unique parent called the of N.
A. Antecedents
B. Predecessor
C. Forerunner
D. Precursor
7. Sequential representation of binary tree uses
A. Array with pointers
B. Single line array
C. Two dimensional arrays
D. Three dimensional arrays
8. A binary tree whose every node has either zero or two children is called
A. complete binary tree
B. binary search tree
C. extended binary tree
D. data structure
9. In a binary-tree, nodes with 0 children are called
A. Exterior node
B. Outside node
C. Outer node
D. External node
14. The maximum number of nodes in a tree for which post-order and pre-order traversals may be equal is ______.
A. 3
B. 1
C. 2
D. any number
16. A binary tree is balanced if the difference between left and right subtree of every node is not more than ___.
A. 1
B. 3
C. 2
D. 0
17. The number of edges from the root to the node is called of the tree.
A. Height
B. Depth
C. Length
D.Width
24. Which of the following tree traversals work if the null left pointer pointing to the predecessor and
null right pointer pointing to the successor in a binary tree?
A. inorder, postorder, preorder traversals
B. inorder
C. postorder
D. preorder
25. What is the maximum number of children that a binary tree node can have?
A. 0
B. 1
C. 2
D. 3
Questions carrying 4 marks
In a complete binary tree, there is exactly one node at level 0, 2 nodes at level 1, 4 nodes at level 2 and so on
b. Forest:
It is the set of disjoint trees. In a given tree, if you remove its root node then itbecomes a forest. In the
above tree, there is a forest with 5 trees.
c. Level:
The entire tree structure is leveled in such a way that the root node is always at level0, then the
intermediate children are at level1 and their intermediate children are atlevel2and so on. The above tree, there
are 4 levels.
d. Depth:
It is the maximum level of any node in a given tree. In the above tree, the root node Ahas the maximum
level. The term height is also used to denote the depth.
2. What do you mean by the following:
a. Degree
b. Terminal and Non-Terminal Node
c. Path
d. Siblings
a. Degree of a node:
It is the number of sub trees of a node in a given tree. In the above tree -
a) Degree of A is 2
b) Degree of C is 2
c) Degree of D is 1
d) Degree of H is 2
e) Degree of K is 0
b. Terminal node:
A node with degree zero is called a terminal node or a leaf. In the above tree, there are7 terminal nodes.
They are K,L ,M,N,G,O and P
Non-terminal Node:
Any node except the root node whose degree is non zero called non-terminalnode, there are 5 non-terminal
nodes. They are B,C,D,E,F,H,I and J
c. Siblings:
The children nodes of a given parent node are called siblings. They are also called brothers. In the above tree,
a) D& E are siblings of parent node B.
b) G & F are siblings of parent node C.
d. Path: it is the sequence of consecutive edges from the source node to the destination node. In theabove
tree, the
path between A and J is given by the node pairs (A,C), (C, F) and(F,J)
A binary tree contains one root node and some non-terminal and terminal nodes. It is clear from the
observation of a binary tree that the non-terminal nodes have their left child nodes. Their lchild and rchild
pointer are set to NULL. Here, non-terminal nodes are called internal nodes and terminal nodes are
called external nodes.
Sequential representation of Binary trees Suppose T is a binary tree that is complete or nearly
complete. Then there is an efficient way of maintaining T in memory called the sequential
representation of T. this representation uses only a single linear array TREE as follows:
Binary trees can be represented either using an array representation or using a linked list representation. The
basic component to be represented in a binary tree is a node.The node consists of 3 fields such as
1) Data
2) Left child
3) Right child
The data filed holds the value to be given. The left child is a link filed which contains the address of its left
node and the right child contains the address of its right node.
class node
{
char data;
Node *lchild;
Node*rchild;
};
Consider a binary tree and its linked list representation is shown in the figure
5. What do you mean by the binary search tree? Write the algorithm to insert and search for anode
in BST.
A binary search tree is a binary tree in which for each node in the tree, the elementsin the left subtree
are less than the root and the elements in the right subtree are greater than or equal to the root.
• Inserting in Binary Search trees
A threaded binary tree is a binary tree in which the nodes that do not have a right child, have a
thread to their inorder successor. By doing this type of threading, we avoid the recursive method of
traversing a tree, which uses stacks and also wastes a lot of memory and time.
J K
L
M
B C
D G
E F
i
j
The preorder traversal of a non-empty binary tree is defined as follows.
In an preorder traversal
After visiting the root node, the left subtree is taken up and it is traversed recursively, then the right
subtree is traversed recursively.
Procedure Preorder(root)
1. If (root !=NULL)
2. Begin
3. Print root-> info
4. Preorder(root-> left)
5. Preorder(root-> right)
6. End
7. finished
B C
D G
E F
i j
In an Inorder traversal
The left subtree is traversed recursively before node. After visiting the root node, the right subtree is taken up
and it is traversed recursively.
Procedure Inorder(root)
1. If (root !=NULL)
2. Begin
3. Inorder(root ->left)
4. Print -> info
5. Inorder(root-> right)
6. End
7. Finished
B C
D G
E F
i
j
The Postorder traversal of a non-root node is visited before traversing its left and right subtrees.
In a Postorder traversal the left and right subtrees are recursively processed before visiting the root. The
left subtree is taken up first and is traversed postorder. Then the right subtree is taken up and is traversed in
postorder. Finally, the data at the root is displayed.
Procedure Postorder(root)
1. If (root!=NULL)
Begin
2. postorder(root ->left)
3. postorder(root ->right)
4. Print root-> info
End
5. Finished
4
15
9 18
INORDER: LEFT-ROOT-RIGHT
4 7 9 14 15 18
PREORDER: ROOT-LEFT-RIGHT
14 4 9 7 15 18
POSTORDER: LEFT-RIGHT-ROOT
7 9 4 18 15 14
A binary search tree is a binary tree in which for each node in the tree, the elementsin the left subtree are
less than the root and the elements in the right subtree are greater than or equal to the root.
MODULE 5
Multiple Choice Questions
(Questions for Application)
4. Is putting an element in the appropriate place in a sorted list yields a larger sortedorder list.
A.insertion
B.extraction
C.selection
D.distribution
5. is rearranging pairs of elements which are out of order, until no such pairs remain.
A. insertion
B. exchange
C. selection
D. distribution
9. Which sorting technique compares the elements that are distant apart?
A.Selection sort
B.Shell sort
C.Insertion sort
D.Quick sort
(Questions for Skill)
10. If the number of records to be sorted is small, then sorting can be efficient.
A.merge
B. heap
C. selection
D. bubble
14. Sorting algorithm is frequently used when n is small where n is total number of
elements.
A.heap
B.insertion
C.bubble
D.quick
22.A path in a digraph in which all the edges are distinct is called
A.Simple path
B.Elementary path
C.Cycle
D.Loop
23. Any two nodes that are connected by an edge in a graph are called _ nodes
A.Directed
B.Adjacent
C.Common
D.Isolated
The algorithm of insertion sort functions as follows. Initially to start the whole array is in a completely
unordered state. The first element is considered to be in the ordered list. The second element is
considered to be in the unordered list. The second element is then inserted either in the first or in the
second position as appropriate. Now there are 2 elements in the ordered part and remaining elements
are considered to be unordered. Inserting the third element, then the fourth and so on slowly extends
the ordered part.
Pass 1: A[1] by itself is sorted because it is the first element
Pass 2: A[2] is inserted either before of after A[1] so that now A[1] , A[2] are sorted.Pass
3: A[3] is inserted into its proper place in A[1], A[2] that is, before A[1], between
A[1]and A[2] or after A[2] so that A[1], A[2], a[3] are sorted.
Pass 4: A[4] is inserted into its proper place in A[1], A[2], A[3] so that: A[1],
A[2], A[3] and A[4] is sorted.
Algorithm I
Procedure InsertionSort( A, N)
OR
Algorithm II
Given an array A of N an element, this procedure sorts the element in the ascending order. The
variables I and J are used to index the array elements.
Procedure Insertion _Sort (A, N)
Step 1:For I =1 to N do
Step 2: TEMP=A[I]
Step 3: J=1-1
Step 4: While (J>=0) and (A[J]>TEMP)
Step 5: A[J+1]=A[J]
Step 6: J=J-1
[End of while loop]
Step 7: A[J+1]=TEMP
[end of step 1 for loop]
Step 8: Exit
In this technique, a single array is divided into two sub lists. The two sub lists are sorted. i.e.
elements from low to mid are sorted and elements from mid+1 to high are sorted. But, the
elements from low to high are unsorted. The efficiency of merge sort is O(n log2 n).
Hence we merge the two sorted sub lists into a single sorted array. If low and high
are lower and upper limits in an array then, the general procedure to implement merge sort is
asfollows:
If(low≤high)
1. Divide the array into equal parts
2. Sort the left part of the array recursively
3. Sort the right part of the array recursively
4. Merge the left and right parts
5. End if
Algorithm:
Algorithm MergeArray(A, LOW,MID,HIGH). This algorithm merges two sorted arrays where
thefirst array is from LOW to MID and the second array is from MID+1 to HIGH.
Algorithm MergeSort(A, LOW, HIGH). The purpose of this algorithm is to sort the elements of
array A between the lower and upper bounds LOW and HIGH respectively.
1. If(LOW≠HIGH) then perform steps 2-5
2. MID←(LOW+HIGH)/2
3. MergeSort(A,LOW,MID)
4. MergeSort(A,MID+1,HIGH)
5. MergeArray(A,LOW,MID,HIGH)
6. Return
Algorithm Linear_Search(A,element,N)
A is an array of N elements and element is the element being searched in the array.
Step 1: Set Loc:=-1
Step 2: Repeat step3 For i=0 to n-1
Step 3: If (Element=A[i]) then
begin
i. Set loc:= i
ii. Goto step 4
[End if]
[End for loop]
Step 4: If (loc>=0) then
i. Write(“Element found at location,loc+1)
ii. Else
iii. Write(“Element not found”)
Step 5:Exit
4. Write the binary search algorithm with an example.
Binary_search( A, element, N)
A is a list of N elements and the element is the element being searched in the array. LOW and HIGH
identify the positions of the 1st and last elements in a range and MID identifies the position the
middle element.
This is a very different approach for traversing the graph nodes. The aim of BFS algorithm is to traverse
the graph as close as possible to the root node. Queue is used in the implementation of the breadth first
search.
Algorithmic Steps
Step 1: Push the root node in the Queue.
Step 2: Loop until the queue is empty.
Step 3: Remove the node from the Queue.
Step 4: If the removed node has unvisited child nodes, mark them as visited
and insert the unvisited children in the queue.
The aim of DFS algorithm is to traverse the graph in such a way that it tries to go far from the root node.
Stack is used in the implementation of the depth first search.
Algorithmic Steps
Step 1: Push the root node in the Stack.
Step 2: Loop until stack is empty.
Step 3: Peek the node of the stack.(Peek used to return the value of top)
Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it as traverse and
push it on stack.
Step 5: If the node does not have any unvisited child nodes, pop the node from the stack.
Step 1: compare A[1] and A[2] and arrange them in the desired order so that A[1] < A[2]. Then
compare A[2] with A[3] and arrange them so that A[2]< A[3]. Continue until we compare A[N-
1] with A[N] and arrange them so that A[N-1] < A[N]. During step 1 the largest element is
bubble up to the A[N] position. And step 1 involves n-1 comparisons.
Step 2: repeat step 1 with one less comparison; that is now we stop after we compare and
possibly arrange A[N-2] and A[N-1] at the end of step 2, the second largest element in the
array will occupy the A[N-1] position.
Step N-1: compare A[1] with A[2] and arrange them so that A[1] < A[2]. After step N-1 steps,
the list will be sorted in increasing order.
Algorithm
Given an array A of N elements, this procedure sorts the elements in the ascending order
using the method described above. The variable I and J are used to index the array elements.
Bubble_Sort (A, N):
Pass 1: find the location POSITION of the smallest element in the list of N elements and then
interchange A[POSITION] and A[1], then A[1] is sorted
Pass 2: find the location POSITION of the smallest element in the sublist of N-1
elementsand then interchange A[POSITION] and A[2] then, A[1] and A[2] are sorted
since A[1]
<=A[2]
Pass 3: find the location POSITON of the smallest element in the sublist of N-2 elements and
then interchange A[POSITION] and A[3] then, A[1], A[2], A[3] is sorted since A[2]<=A[1].
And so on. Thus A is sorted after N-1 passes.
Algorithm
A is an array of N elements. This algorithm finds the smallest element SMALL and its
location POSITION among the elements in the array A.
Procedure SelectionSort(A, N)
Algorithm:
PARTITION ALGORITHM:
Partition(A, LOW,HIGH)
This function partitions the array A with LOW and HIGH as lower boundand upper bound respectively
into two sub lists.
This is a recursive algorithm to sort the elements in array Awith LOW and HIGH as lower and upper
bound respectively.