Unit-III Stack Notes
Unit-III Stack Notes
STACK
Stack is a Linear Data Structure that follows Last In First Out(LIFO) principle.
Insertion and deletion can be done at only one end of the stack called TOP of the stack.
Example: - Pile of coins, stack of trays
STACK ADT:
STACK MODEL
TOP pointer
Two fundamental operations performed on the stack are PUSH and POP.
(a) PUSH:
1. Stack Overflow
An Attempt to insert an element X when the stack is Full, is said to be stack
overflow.
For every Push operation, we need to check this condition.
2. Stack Underflow:
return(1);
int TopElement(Stack S)
{
if(Top==-1)
{
Error(“Empty stack!!No elements”);
return 0;
}
else
return S[Top];
}
#include<stdio.h>
#include<conio.h>
#define size 5
int stack [ size ];
int top;
void push( )
{
int n ;
printf( "\n Enter item in stack" ) ;
scanf( " %d " , &n ) ;
if( top = = size - 1)
{
printf( "\nStack is Full" ) ;
}
else
{
top = top + 1 ;
stack [ top ] = n ;
}
}
void pop( )
{
int item;
if( top = = - 1)
{
printf( "\n Stack is empty" );
}
else
{
item = stack[ top ] ;
printf( "\n item popped is = %d" , item );
top - -;
}
}
void display( )
{
int i;
printf("\n item in stack are");
for(i = top; i > = 0; i --)
printf("\n %d", stack[ i ] );
}
void main( )
{
char ch,ch1;
ch = 'y';
ch1 = 'y';
top = -1;
clrscr( );
while(ch !='n')
{
push( );
printf("\n Do you want to push any item in stack y/n");
ch=getch( );
}
display( );
while( ch1!='n' )
{
printf("\n Do you want to delete any item in stack y/n");
ch1=getch( );
pop( );
}
display( );
getch( );}
UTPUT:
Enter item in stack20
Do you want to push any item in stack y/n
Enter item in stack25
Do you want to push any item in stack y/n
Enter item in stack30
Stack is Full
Do you want to push any item in stack y/n
item in stack are
25
20
15
10
5
Do you want to delete any item in stack y/n
item popped is = 25
Do you want to delete any item in stack y/n
item popped is = 20
Do you want to delete any item in stack y/n
item popped is = 15
item in stack are
10
5
Linked list implementation of Stack
Stack elements are implemented using SLL (Singly Linked List) concept.
Dynamically, memory is allocated to each element of the stack as a node.
Type Declarations for Stack using SLL
struct node;
typedef struct node *stack;
typedef struct node *position;
stack S;
struct node{ int
data; position
next;};
int IsEmpty(Stack S);
void Push(int x, Stack S);
void Pop(Stack S);
int TopElement(Stack S);
(i) Stack Empty Operation:
Initially Stack is Empty.
With Linked List implementation, Empty stack is represented as S -> next = NULL.
It is necessary to check for Empty Stack before deleting ( pop) an element from the stack.
Routine to check whether the stack is empty S
S
Header
30 20 10 NULL
40
newnode
Before Insertion
Push routine /*Inserts element at front of the list
void push(int X, Stack S)
{
Position newnode, Top;
newnode = malloc (sizeof( struct node ) );
newnode -> data = X;
newnode -> next = S -> next;
S -> next = newnode;
Top = newnode;
}
Header
40 30 20 10 NULL
After Insertion
TO
(iii) Pop Operation
It is the process of deleting the Top element of the stack.
With Linked List implementations, the element at the Front of the
List (i.e.) S -> next is always deleted.
It takes only one parameter. Pop(X).The element X to be deleted from the Front of
the List.
Before deleting the front element in the list, check for Empty Stack.
If the Stack is Empty, deletion is not possible.
Otherwise, make the front element in the list as “temp”.
Update the next field of header.
Using free ( ) function, Deallocate the memory allocated for temp node.
PANIMAL R
A S
www.padeepz.net
Heade
r
40 30
20 10 NULL
TOP
Before Deletion
Pop routine /*Deletes the element at front of list
void Pop( Stack S )
{
Position temp, Top;
Top = S -> next;
if( S -> next = = NULL)
Error(“empty stack! Pop not possible”);
else
{
Temp = S -> next;
S -> next = temp -> next;
free(temp);
Top = S -> next;
}}
Heade
r
40 30 20 10 NULL
HEAD
ER
30 20 10 NULL
A
fter Deletion
(iv) Return Top Element
Pop routine deletes the Front element in the List.
If the user needs to know the last element inserted into the stack, then the user
can return the Top element of the stack.
To do this, first check for Empty Stack.
If the stack is empty, then there is no element in the stack.
Otherwise, return the element present in the S -> next -> data in the List.
if(S->next==NULL)
error(“Stack is empty”);
return 0;
else
return S->next->data;
Heade
r
40 30 20 10 NULL
TOP
Implementation of stack using 'Linked List'
case 4:
display();
break;
case 5:
exit(0);
}
}while(op<5);
getch();
}
void create()
{
int n,i;
s=NULL;
printf("Enter the no of nodes to be created\n");
scanf("%d",&n);
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data\t");
scanf("%d",&newnode->data);
newnode->next=NULL;
top=newnode;
s=newnode;
for(i=2;i<=n;i++)
{
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data\t");
scanf("%d",&newnode->data);
newnode->next=top;
s=newnode;
top=newnode;
}}
void display()
{ top=s; while(top!
=NULL)
{
printf("%d->",top->data);
top=top->next;
}
printf("NULL\n");
}
void push()
{ top=s;
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data\t");
scanf("%d",&newnode->data);
newnode->next=top;
top=newnode;
s=newnode;
display();
}
void pop()
{
top=s;
if(top==NULL)
printf("Empty stack\n\n");
else
{
temp=top;
printf("Deleted element is \t %d\n\n",top-
>data); s=top->next;
free(temp);
display();
}}
Output
### Linked List Implementation of STACK Operations ###
Press 1-create
2-Push
3-Pop
4-Display
5-Exit
Your option ? 1
Enter the no of nodes to be created5
Enter the data 10
Enter the data20
Enter the data30
Enter the data40
Enter the data50
### Linked List Implementation of STACK Operations ###
Press 1-create
2-Push
3-Pop
4-Display
5-Exit
Your option ? 4
50->40->30->20->10->NULL
### Linked List Implementation of STACK Operations ###
Press 1-create
2-Push
3-Pop
4-Display
5-Exit
Your option ?2
Enter the data60
Your option ? 4
60->50->40->30->20->10->NULL
Your option ?2
Enter the data70
Your option ? 4
70->60->50->40->30->20->10->NULL
Your option ?3
Deleted element is70
Your option ? 4
50->40->30->20->10->NULL
Applications of Stack
INFIX:
The arithmetic operator appears between the two operands to which it is being
applied.
POSTFIX:
The arithmetic operator appears directly after the two operands to which it applies.
Also called reverse polish notation.
PREFIX:
The arithmetic operator is placed before the two operands to which it applies. Also
called polish notation.
Read the infix expression one character at a time until it encounters the delimiter “#”
Step 2: If the character is an operator, push it onto the stack. If the stack operator has a higher or
equal priority than input operator then pop that operator from the stack and place it onto the
output.
Step 3:If the character is left parenthesis, push it onto the stack
Step 4:If the character is a right parenthesis, pop all the operators from the stack till it encounters
left parenthesis, discard both the parenthesis in the output.
E.g. Consider the following Infix expression: - A*B+(C-D/E)#
A A
*
A
B
+ AB
*
+ AB*
( AB*
(
+
Read char Stack Output
C AB*C
(
+
- - AB*C
(
+
- AB*CD
D
(
+
/ / AB*CD
-
(
+
/ AB*CDE
E
-
(
+
AB*CDE/-
) /
-
(
+
Read char Stack Output
AB*CDE/-+
Read the postfix expression one character at a time until it encounters the delimiter „#‟
Step 1: If the character is an operand, push its associated value onto the stack.
Step 2: If the character is an operator, POP two values from the stack, apply the operator to
them and push the result onto the stack.
Operand Value
A 2
B 3
C 4
D 4
E 2
A 2
3
B
2
Char Read Stack
* 6
4
C 6
4
D 4
6
2
/ 4
6
2
- 6
+ 8
OUTPUT = 8
(
(
a a
(
+ a
+
(
b ab
+
(
) ab+
* ab+
c ab+c
ab+c*
/
d ab+c*
d
ab+c*d
+ /
21
e ab+c*d/e
/ ab+c*d/e
/
+
f ab+c*d/ef
/
+
# ab+c*d/
ef/+
Operand Value
a 1
b 2
c 4
d 2
e 6
f 3
Char Read Stack
a 1
2
b
1
+ 3
4
c 3
* 12
2
d 12
/ 6
6
e 6
3
F 6
6
2
/ 6
+ 8
Output = 8
Infix to Postfix Conversion Output
#define SIZE 50 /* Size of Stack */
#include <ctype.h>
char s[SIZE];
int top=-1; /* Global declarations */
char pop()
{
return(s[top--]);
} (a+b)-(c-d)
Void main()
{ /* Main Program
*/ char infx[50],pofx[50],ch,elem;
int i=0,k=0;
printf("\nRead the Infix Expression ?
"); scanf("%s",infx);
push('#');
while( (ch=infx[i++]) != '\0')
{
if( ch == '(')
push(ch); else
if(isalnum(ch)) pofx[k++]=ch;
else
if( ch == ')')
{
while( s[top] != '(')
pofx[k++]=pop();
elem=pop(); /* Remove */
}
else
{ /* Operator */
while( pr(s[top]) >= pr(ch) )
pofx[k++]=pop();
push(ch);
}
}
while( s[top] != '#') /* Pop from
stack till empty
pofx[k++]=pop();
pofx[k]='\0'; /* Make pofx as
valid string */
printf("\n\nGiven Infix Expn: %s Postfix
Expn: %s\n",infx,pofx);
}
Towers of Hanoi
Towers of Hanoi can be easily implemented using recursion. Objective of the problem is
moving a collection of N disks of decreasing size from one pillar to another pillar. The
movement of the disk is restricted by the following rules.
Rule 2 : No larger disk could ever reside on a pillar on top of a smaller disk.
Rule 3 : A 3rd pillar could be used as an intermediate to store one or more disks, while they
A B C
Step 2. If N = 2, move the 1st disk from A to B. Then move the 2nd disk from A to C, The move
the 1st disk from B to C.
Step 3. If N = 3, Repeat the step (2) to more the first 2 disks from A to B using C as
intermediate. Then the 3rd disk is moved from A to C. Then repeat the step (2) to move 2 disks
from B to C using A as intermediate.
In general, to move N disks. Apply the recursive technique to move N - 1 disks from A to B
using C as an intermediate. Then move the N th disk from A to C. Then again apply the recursive
technique to move N - 1 disks from B to C using A as an intermediate
O(N)=O(N-1)+1+O(N-1) =2N-1
Function Calls
When a call is made to a new function all the variables local to the calling routine need to
be saved, otherwise the new function will overwrite the calling routine variables. Similarly the
current location address in the routine must be saved so that the new function knows where to go
after it is completed.
Cal
l
balance() Call
push()
Recursive Function to Find Factorial
int fact(int n)
{
int S;
if(n==1)
return(1);
else
S = n * fact( n – 1 );
return(S)
}
Compilers check the programs for errors, a lack of one symbol will cause an error.
A Program that checks whether everything is balanced.
Every right parenthesis should have its left parenthesis.
Check for balancing the parenthesis brackets braces and ignore any other character.
((B*B)-{4*A*C}/[2*A]) #
( (
(
)
(
{ {
(
}
(
[ [
(
]
(
Gate questions and
answers
Stacks and Queues
1. Compute the postfix equivalent of the following infix arithmetic expression where a+b*c+d*e↑f; where ↑ represents
exponentiation. Assume normal operator precedence.
1 a+b*c+d*e↑f
2 +b*c+d*e↑f a
3 b*c+d*e↑f a +
4 *c+d*e↑f ab +
5 c+d*e↑f ab +*
6 +d*e↑f abc +*
7 d*e↑f abc*+ +
8 *e↑f abc*+d +
9 e↑f abc*+d +*
10 ↑f abc*+de +*
11 f abc*+de +* ↑
12 abc*+def +* ↑
abc*+def↑*+
2. Suppose one character at a time comes as an input from a string of letters. There is an option either to (i) print the
incoming letter or to (ii) put the incoming letter on to a stack. Also a letter from top of the stack can be
popped out at any time and printed. The total number of total distinct words that can be formed out of a string
of three letters in this fashion, is
(A)
(B)
(C)
Total no of distict word can be 5.
Total no of words starting with c will be 1 (cba) because to print c as first letter we have to push a and b in stack
PUSH (10), PUSH (20), POP, PUSH (10), PUSH (20), POP, POP, POP, PUSH (20), POP.
[B]
Push(10) 10
Push(20) 10 20
Pop 10 20
Push(10) 10 10 20
Push(20) 10 10 20 20
Pop 10 10 20 20
Pop 10 20 20 10
Pop 20 20 10 10
Push(20) 20 20 20 10 10
Pop 20 20 10 10 20
4. A stack is use to pass parameters to procedures in a procedure call.
P(a,b)
State precisely in a sentence what is pushed onto stack for parameters a and b.
In the generated code for the body of procedure P, how will the addressing of formal parameters y and y differ?
5. Which of the following permutation can be obtained in the output (in the same order) using a stack assuming that the
input is the sequence1, 2, 3, 4, 5 in that order?
(A) 3, 4, 5, 1, 2
(B) 3, 4, 5, 2, 1
(C) 1, 5, 2, 3, 4
(D) 5, 4, 3, 1, 2
[A] As it can be verified as- push(1) push(2) push(3) pop push(4) pop push(5) pop pop pop
6.
A + B*(C+D)/F + D*E is
(a) AB+CD+*F/D+E*
(b) ABCD+*F/DE*++
(c) A*B+CD/F*DE++
(d) A+*BCD/F*DE++
Possible Answer:
A+B*(C+D)/F+D*E
+B*(C+D)/F+D*E A
B*(C+D)/F+D*E A +
*(C+D)/F+D*E AB +
(C+D)/F+D*E AB +
C+D)/F+D*E AB +*(
+D)/F+D*E ABC
D)/F+D*E ABCD
/F+D*E ABCD+ +*
F+D*E ABCD+* +/
+D*E ABCD+*F +/
D*E ABCD+*F/+ +
*E ABCD+*F/+ +*
E ABCD+*F/+DE +*
ABCD+*F/+DE*+
(A) (ii) and (iii) are true (B) (i) and (ii) are true
(C) (iii) and (iv) are true (D) (ii) and (iv) are true
[A]
Queue using linked list are efficient in using memory. They do not waste space like in array implementation .
3 * log (x + 1) – a/2
3X1+log*a2/- (assuming log as a operator not as a function and precedence of log is greatest)
9. A queue Q containing n items and an empty stack S are given. It is required to transfer all the items from the queue to
the stack, so that the item at the front of the queue is on the top of the stack, and the order of all the other
items is preserved. Show this how this can be done in O(n) time using only a constant amount of additional
storage. Note that the only operations which can be performed on the queue and stack are Delete, Insert,
Push and Pop. Do not assume any implementation of the queue or stack.
It can be done as –
Step1. Delete all the nodes of queue and push all the elements in stack sequentially.
Step2. Now queue is empty then pop every element form stack and inset it into queue
10. Which of the following is essential for converting an infix expression to the postfix form efficiently?
[A] Operater stack will be used to store operaters as the appear based on three rules
1. if operater ‘x’ is on top and operater ‘y’comes which has a higher precedence than x the it will also be
pushed to stack..
2. if x and y have same precedence then x will be poped out before y is pushed
3. same as rule 2 if x has a higher precedence than y.
11. A priority queue Q is used to implement a stack S that stores characters. PUSH(C) is implemented as INSERT(Q,
C, K) where K is an appropriate integer key chosen by the implementation. POP is implemented as
DELETEMIN(Q). For a sequence of operations, the keys chosen are in
[D] Implementing stack using priority queue require first element inserted in stack will be deleted at last, and to
implement it using deletemin() operation of queue will require first element inserted must have highest
priority so the key must be in decreasing order.
12. Suppose a stack implementation supports, in addition to PUSH and POP, an operation REVERSE, which reverses
the order of the elements on the stack.
(a) To implement a queue using the above stack implementation, show how to implement ENQUEUE using a
single operation and DEQUEUE using a sequence of 3 operations (2)
(b) The following postfix expression, containing single digit operands and arithmetic operators + and *, is
evaluated using a stack.
52*34+52**+
a)
Step1: reverse
Step2: pop
Step3:reverse
i After evaluating 5 2 * 3 4 +
ii After evaluating 5 2 * 3 4 + 5 2
iii At the end of evaluation
b)
5 5
2 52
* 10 5*2=10
3 10 3
4 10 3 4
+ 10 7 3+4=7
5 10 7 5
2 10 7 5 2
* 10 7 10 5*2=10
* 10 70 7*10=70
+ 80
Null
13. What is the minimum number of stacks of size n required to implement a queue of size n?
A. One
B. Two
C. Three
D. Four
[B] First stack will be used to store the queue with rear at top..
For deletion we will empty stack 1 in stack 2.that will put front on top so we can pop from stack 2 in order to effect
deletion.
14. Let S be a stack of size n ≥ 1. Starting with the empty stack, suppose we Push the first n natural numbers in
sequence, and then perform n Pop operations. Assume that Push and POP operations take X seconds each, and Y
seconds elapse between the end of one such stack operation and the start of the next operation. For m ≥ 1, define the
stack-life of m as the time elapsed from the end of Push(m) to the start of the Pop operation that removes m from S.
The average stack-life of an element of this stack is
(A) n(X + Y)
(B) 3Y + 2X
(C) N(X + Y) – X
(D) Y + 2X
[A]
Push1() and pop1() are push and pop operations in 1st stack
Push2() and pop2() are push and pop operations in 2nd stack
Using 1st stack we can insert value same as queue (push1())
And for deletion we have to pop all the elements of 1st stack into push it into 2nd stack and then pop one element form
2nd stack.(pop1()push2()…..until 1st stack is emptied then pop2()…for desired number of deletion )
PUSH (10), PUSH (20), POP, PUSH (10), PUSH (20), POP, POP, POP, PUSH (20), POP.
[G]
Push(10) 10
Push(20) 10 20
Pop 10 20
Push(10) 10 10 20
Push(20) 10 10 20 20
Pop 10 10 20 20
Pop 10 20 20 10
Pop 20 20 10 10
Push(20) 20 20 20 10 10
Pop 20 20 10 10 20
16. Consider three pegs A, B, C and four disks of different sizes. Initially, the four disks are stacked on peg A, in order
of decreasing size. The task is to move all the disks from peg A to peg C with the help of peg B. the
moves are to be made under the following constraints:
[i] In each step, exactly one disk is moved from one peg to another.
[ii] A disk cannot be placed on another disk of smaller size. If we denote the movement of a disk from one
peg to another by y → y, where y, y are A, B or C, then represent the sequence of the minimum number
of moves to accomplish this as a binary tree with node labels of the form (y → y) such that the in-order
traversal of the tree gives the correct sequence of the moves..
If there are n disks, derive the formula for the total number of moves required in terms of n
2 disks 22-1=3
3 disks 32-1=7
4 disks 42-1=15
……. ……….
……. ……….
State precisely in a sentence what is pushed onto stack for parameters a and b.
In the generated code for the body of procedure P, how will the addressing of formal parameters y and y differ?
18. Which of the following permutation can be obtained in the output (in the same order) using a stack assuming that
the input is the sequence1, 2, 3, 4, 5 in that order?
(E) 3, 4, 5, 1, 2
(F) 3, 4, 5, 2, 1
(G) 1, 5, 2, 3, 4
(H) 5, 4, 3, 1, 2
[F] As it can be verified as- push(1) push(2) push(3) pop push(4) pop push(5) pop pop pop
#include<stdio.h>
#define EOF -1
void flagError();
int main( )
{ int c, m, n, r;
{ if (isdigit(c))
push (c)
{ m = pop( );
n = pop( );
push(r);
else if (c != ‘ ‘)
flagError( );
52*332+*+
1. push(5)
2. push(2)
3. m = 2;n=5 ;r=5*2
4. push(r) /*push(10)*/
5. push(3)
6. push(3)
7. push(2)
8. m=2; n= 3;r=3+2
9. push(r) /* push(5)*/
10. r=5*3
11. push(r) /*push(15)*/
12. m=15;n = 10;r=15+10
13. push(r)
14. printf(“%d”,pop());
20. Suppose you are given an implementation of a queue of integers. The operations that can be performed on the
queue are:
delete(Q) – deletes the element at the front of the queue and returns its value.
void f(queue Q)
int i;
if(!isEmpty (Q)) {
i = delete(Q);
f(Q)
insert(Q, i);
[B] Due to recursion the last element deleted will be the first to be inserted so element that was at rear will be at
front in new queue and the second last element will be at second position hence the queue will be reversed.
21. Let w be the minimum weight among all edge weights in an undirected connected graph. Let e be a specific edge of
weight w. Which of the following is FALSE?
[D]
int f(int n)
If (n < = 0) return 1;
If (n > 3)
{ r = n;
return f (n – 2) + 2;
return f(n – 1) + r;
}
[D]
23. The following postfix expression with single digit operands is evaluated using a stack:
823^/23*+51*-
Note that ^ is the exponentiation operator. The top two elements of the stack after the first *is evaluated are:
[A]
8 8
82 82
823 823
8 2 3^ 88
8 2 3^/ 1
8 2 3^/2 12
8 2 3^/2 3 123
8 2 3^/2 3 * 16
print ( “ Q is empty” );
return;
x = pop (S1);
x = pop (S2);
Let n insert and m (≤ n) delete operations be performed in an arbitrary order on an empty queue Q. let x and y be the
number of push and pop operations performed respectively in the process. Which one of the following is true for all
m and n?
[A]
Extreme case will be when all the elements are inserted and then deleted
And for first delete we have n push operations if n elements are in stack, so n+m<=x in worst case
And no of pushes is also 2n : n for n insert and n for first delete
So (n+m)<= x < 2n
Also n pops for first delete and m-1 one pops for m-1 deletes so y= n+m-1 in extreme case y< n+m-1
f(ф) = 0 and
If a stack S contains the integers 2, -3, 2, -1, 2 in order from bottom to top, what is f(S)?
[C] Answer is 3
Step1:top s=2
Step2: tops= -1
Step3: tops= 2
26. Assume that the operators +, -, × are left associative and ^ is right associative. The order of precedence (from
highest to lowest) is ^, ×, +, -. The postfix expression corresponding to the infix expression a+b×c-d^e^f is
(A) abc×+def ^ ^ -
(B) abc×+de ^ f ^ -
(C) ab+c×d-e ^f ^
(D) -+a×bc ^ ^ def
[A]
Infix string Stack Postfix array
a a
+ + a
b + ab
* +* ab
c +* abc
- - abc*+
d - abc*+d
^ -^ abc*+d
e -^ abc*+de
f -^^ abc*+def
-^ abc*+def^
- abc*+def^^
abc*+def^^-
27. The best data structure to check whether an arithmetic expression has balanced parenthesis is a
(A) Queue
(B) Stack
(C) Tree
(D) List
[B]We can put every opening parenthesis in stack and pop every time we get a closed one. In
the ened if we get stack empty then we had balanced parenthesis else not.
Binary Tree using Array Representation
Each node contains info, left, right and father fields. The left, right and father
fields of a node point to the node’s left son, right son and father respectively.
Example: -
A
B
-
C
-
-
-
D
-
0 1
A A
B 1 C 2 B C
2 3
D E F G D E F G
3 4 5 6 4 5 6 7
A B C D E F G A B C D E F G
0 1 2 3 4 5 6 1 2 3 4 5 6 7
For Figure 2.5 For Figure 2.6
Root = i Root = i
leftchild=2i+1 leftchild=2i
www.padeepz.n
www.padeepz.net et
www.padeepz.n
rightchild=2i+2
et
rightchild=2i+1
www.padeepz.n
www.padeepz.n
et
Fig (a) Fig (b)
Struct treenode
{
int data;
structtreenode *leftchild;
structtreenode *rightchild;
}*T;
T
2000
1000 1 1006
1000 1006
1008 5 1010
1002 2 1004
www.padeepz.n
www.padeepz.n
et
A
B C
www.padeepz.n
www.padeepz.n
et
General Tree:
A General Tree is a tree in which each node can have an unlimited out degree.
Each node may have as many children as is necessary to satisfy its
requirements. Example: Directory Structure
A
B F G
C H I J
It is considered easy to represent binary trees in programs than it is to
represent general trees. So, the general trees can be represented in binary
tree format.
The binary tree format can be adopted by changing the meaning of the left and
right pointers. There are two relationships in binary tree,
Parent to child
Sibling to sibling
Using these relationships, the general tree can be implemented as binary tree.
Algorithm
Identify the branch from the parent to its first or leftmost child. These
branches from each parent become left pointers in the binary tree
Connect siblings, starting with the leftmost child, using a branch for each
sibling to its right sibling.
Remove all unconnected branches from the parent to its children
A
B E F
C D G H I
www.padeepz.n
www.padeepz.n
et
(a) General Tree
A A
B B E F
C D G I C D G H I
A
B E F
C B D G H I
Step 3: Delete unneeded branches
C E
D F
G
THE RESULTING BINARY TREE
H
Compared to linear data structures like linked lists and one dimensional
array, which have only one logical means of traversal, tree structures can be
traversed in many different ways. Starting at the root of a binary tree, there
are three main steps that can be performed and the order in which they are
performed defines the traversal type. These steps (in no particular order) are:
performing an action on the current node (referred to as "visiting" the node),
www.padeepz.n
www.padeepz.n
et
traversing to the left child node, and traversing to the right child node. Thus
the process is most easily described through recursion.
A binary tree traversal requires that each node of the tree be processed once
and only once in a predetermined sequence.
The two general approaches to the traversal sequence are,
Depth first traversal
Breadth first traversal
Breadth-First Traversal
Depth-First Traversal
In depth first traversal, the processing proceeds along a path from the root
through one child to the most distant descendent of that first child before
www.padeepz.n
www.padeepz.n
et
processing a second child. In other words, in the depth first traversal, all the
descendants of a child are processed before going to the next child.
www.padeepz.n
www.padeepz.n
et
Inorder Traversal
Steps :
Traverse left subtree in inorder
Process root node
Traverse right subtree in inorder
B E
C D F
The Output is : C B D A E F
Algorithm
Algorithm inoder traversal (BinTree T)
Begin
If ( not empty (T) ) then
Begin
Inorder_traversal ( left subtree ( T ) )
Print ( info ( T ) ) / * process node */
Inorder_traversal ( right subtree ( T ) )
End
End
Routines
void inorder_traversal ( NODE * T)
{
if( T ! = NULL)
{
www.padeepz.n
www.padeepz.n
inorder_traversal(T->lchild);
et
printf(“%d \t “, T->info);
inorder_traversal(T->rchild);
}
}
Preorder Traversal
Steps :
Process root node
Traverse left subtree in preorder
Traverse right subtree in preorder
Algorithm
Algorithm inoder traversal (BinTree T)
Begin
If ( not empty (T) ) then
Begin
Print ( info ( T ) ) / * process node */
Preorder_traversal ( left subtree ( T ) )
Preorder_traversal ( right subtree ( T )
) End
End
Routines
void inorder_traversal ( NODE * T)
{
if( T ! = NULL)
{
printf(“%d \t “, T->info);
preorder_traversal(T->lchild);
preorder_traversal(T->rchild);
}
}
B
E
www.padeepz.net
www.padeepz.n
et
Output is : A B C D E F
Postorder Traversal
Steps :
Traverse left subtree in postorder
Traverse right subtree in postorder
process root node
Algorithm
Algorithm postorder traversal (BinTree T)
Begin
If ( not empty (T) ) then
Begin
Postorder_traversal ( left subtree ( T ) )
Postorder_traversal ( right subtree( T))
Print ( Info ( T ) ) / * process node */
End
End
Routines
void postorder_traversal ( NODE * T)
{
if( T ! = NULL)
{
postorder_traversal(T->lchild);
postorder_traversal(T->rchild);
printf(“%d \t”, T->info);
www.padeepz.n
www.padeepz.n
}
et
}
B
E
C D F
Output is : C D B F E A
A
Examples :
B
C
D E F G
www.padeepz.n
www.padeepz.n
ANSWER : POSTORDER: DEBFGCA INORDER: DBEAFCG
et
PREORDER:ABDECFG
3.A BINARY TREE HAS 8 NODES. THE INORDER AND POSTORDER TRAVERSAL OF THE
TREE ARE GIVEN BELOW. DRAW THE TREE AND FIND PREORDER.
POSTORDER: F E C H G D B A
INORDER: FCEABHDG
A
Answer:
C B
D
F E
H
G
PREORDER: ACFEBDHG
Example 4
www.padeepz.n
www.padeepz.n
et
APPLICATIONS
EXPRESSION TREES
a/b+(c-d)e
www.padeepz.n
www.padeepz.n
et
Algorithm
1) Examine the next element in the input.
2) If it is an operand, output it.
3) If it is opening parenthesis, push it on stack.
4) If it is an operator, then
i) If stack is empty, push operator on stack.
ii) If the top of the stack is opening parenthesis, push operator on stack.
iii) If it has higher priority than the top of stack, push operator on stack.
iv) Else pop the operator from the stack and output it, repeat step 4.
5) If it is a closing parenthesis, pop operators from the stack and output
them until an opening parenthesis is encountered. pop and discard the
opening parenthesis.
6) If there is more input go to step 1
7) If there is no more input, unstack the remaining operators to output.
Example
Suppose we want to convert 2*3/(2-1)+5*(4-1) into Prefix form: Reversed
Expression: )1-4(*5+)1-2(/3*2
www.padeepz.n
www.padeepz.n
et
3 * 23
/ / 23*
( /( 23*
2 /( 23*2
- /(- 23*2
1 /(- 23*21
) / 23*21-
+ + 23*21-/
5 + 23*21-/5
* +* 23*21-/5
( +*( 23*21-/5
4 +*( 23*21-/54
- +*(- 23*21-/54
1 +*(- 23*21-/541
) +* 23*21-/541-
Empty 23*21-/541-*+
Algorithm
1) Reverse the input string.
2) Examine the next element in the input.
3) If it is operand, add it to output string.
4) If it is Closing parenthesis, push it on stack.
5) If it is an operator, then
www.padeepz.n
www.padeepz.n
i) If stack is empty, push operator on stack.
et
ii) If the top of stack is closing parenthesis, push operator on stack.
iii) If it has same or higher priority than the top of stack, push operator
on stack.
iv) Else pop the operator from the stack and add it to output string,
repeat step 5.
6) If it is a opening parenthesis, pop operators from stack and add them to
output string until a closing parenthesis is encountered. Pop and discard
the closing parenthesis.
7) If there is more input go to step 2
8) If there is no more input, unstack the remaining operators and add them
to output string.
9) Reverse the output string.
Example
www.padeepz.n
www.padeepz.n
et
/ +/ 14-5*12-
3 +/ 14-5*12-3
* +/* 14-5*12-3
2 +/* 14-5*12-32
Empty 14-5*12-32*/+
Reverse the output string : +/*23-21*5-41 So, the final Prefix Expression is
+/*23-21*5-41
EVALUATION OF EXPRESSIONS
www.padeepz.n
www.padeepz.n
et
CONSTRUCTING AN EXPRESSION TREE
Let us consider the postfix expression given as the input, for constructing an
expression tree by performing the following steps :
1. Read one symbol at a time from the postfix expression.
2. Check whether the symbol is an operand or operator.
i. If the symbol is an operand, create a one node tree and push
a pointer on to the stack.
ii. If the symbol is an operator, pop two pointers from the
stack namely, T1 and T2 and form a new tree with root as the
operator, and T2 as the left child and T1 as the right child.
iii. A pointer to this new tree is then pushed on to the stack.
ab+cde+**
The first two symbols are operands, so we create one-node trees and push
pointers to them onto a stack.*
*For convenience, we will have the stack grow from left to right in the
diagrams.
www.padeepz.n
www.padeepz.n
et
Next, a '+' is read, so two pointers to trees are popped, a new tree is formed,
and a pointer to it is pushed onto the stack.*
Next, c, d, and e are read, and for each a one-node tree is created and a pointer
to the corresponding tree is pushed onto the stack.
www.padeepz.n
www.padeepz.n
et
Continuing, a '*' is read, so we pop two tree pointers and form a new tree
with a '*' as root.
Finally, the last symbol is read, two trees are merged, and a pointer to the final
tree is left on the stack.
www.padeepz.n
www.padeepz.n
et
Binary search tree (BST) is a node-based binary tree data structure which
has the following properties:
The left sub-tree of a node contains only nodes with keys less than the
node's key.
The right sub-tree of a node contains only nodes with keys greater than
the node's key.
Both the left and right sub-trees must also be binary search trees.
www.padeepz.n
www.padeepz.n
Each node (item in the tree) has a distinct key.
et
struct tnode
{
int data;
struct tnode *lchild,*rchild;
};
www.padeepz.n
www.padeepz.n
et
p = (struct tnode *) malloc(sizeof(struct tnode)); /* insert the new node
as root node*/
if(p == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
p->data = val;
p- >lchild=p->rchild=NULL;
}
else
{
temp1 = p;
/* traverse the tree to get a pointer to that node whose child will be the newly
created node*/
while(temp1 != NULL)
{
temp2 = temp1;
if( temp1 ->data > val)
temp1 = temp1->lchild;
else
temp1 = temp1->rchild;
}
if( temp2->data > val)
{
temp2->lchild = (struct tnode*)malloc(sizeof(struct tnode));/*inserts the
newly created node as left child*/
temp2 = temp2->lchild;
if(temp2 == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
else
{
www.padeepz.n
www.padeepz.n
et
temp2->rchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the
newly created node
as left child*/
temp2 = temp2->rchild;
if(temp2 == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
}
return(p);
}
/* a function to binary tree in inorder */
void inorder(struct tnode *p)
{
if(p != NULL)
{
inorder(p->lchild);
printf("%d\t",p->data);
inorder(p->rchild);
}
}
void main()
{
struct tnode *root = NULL;
int n,x;
printf("Enter the number of nodes\n");
scanf("%d",&n);
while( n - > 0)
{
printf("Enter the data value\n");
scanf("%d",&x);
root = insert(root,x);
}
inorder(root);
www.padeepz.n
www.padeepz.n
}
et
4 5
7 1
So
2
4
4
5
7
and 1<2 so
2
4
www.padeepz.n
www.padeepz.n
et
5
1
7
is the final BST.
OPERATIONS
www.padeepz.n
www.padeepz.n
};
et
Make_null
SEARCH_TREE
make_null ( void )
{
return NULL;
}
Find
www.padeepz.n
www.padeepz.n
T=T-->left;
et
}
else if(num< T-->data)
{
T=T-->left;
if(num>T-->data)
T=T-->right;
}
if(T-->data==num)
break;
}
return T;
}
// To find a Number
Position find(elementtype X, searchtree T)
{ If(T==NUL
L)
return NULL;
if(x< T-->element)
return find(x,T-->left);
else if(X> T-->element)
return find(X,T-->right);
else
return T;
}
www.padeepz.n
www.padeepz.n
return NULL;
et
else if(T-->left==NULL)
return T;
else return findmin(T-->left);
}
// Finding Maximum
Position findmax(searchtree T)
{ if(T==NUL
L)
return NULL;
else if(T-->right==NULL)
return T;
else return findmin(T-->right);
}
www.padeepz.n
www.padeepz.n
Insert
et
Figure shows the code for the insertion routine. Since T points to the root of
the tree, and the root changes on the first insertion, insert is written as a
function that returns a pointer to the root of the new tree. Lines 8 and 10
recursively insert and attach x into the appropriate subtree.
www.padeepz.n
www.padeepz.n
{
et
If(T== NULL)
{
/* create and return a one node tree*/
T=malloc(sizeof(structtreenode));
If(T==NULL)
Fatalerror(“Out of Space”);
Else
{
T-->element=X;
T-->left=T-->right=NULL;
}
}
Else if(x<T-->element)
T-->left=insert(X,T-->left);
Else if(X>=T-->left)
T-->right=insert(X,T-->right);
Return T;
}
www.padeepz.n
www.padeepz.n
STEP 1: Now 5<6 and 5>2 and 5<4 so
et
Thus 5 is inserted.
Delete
If the node is a leaf, it can be deleted immediately. If the node has one child,
the node can be deleted after its parent adjusts a pointer to bypass the node
(we will draw the pointer directions explicitly for clarity).. Notice that the
deleted node is now unreferenced and can be disposed of only if a pointer to
it has been saved. The complicated case deals with a node with two children.
The general strategy is to replace the key of this node with the smallest key of
the right subtree (which is easily found) and recursively delete that node
(which is now empty). Because the smallest node in the right subtree cannot
have a left child, the second delete is an easy one.
www.padeepz.n
www.padeepz.n
Case 1: Node to be deleted is a leaf node.
et
Case 2: Node with only one child.
Case 3: Node with two children.
Case 1:
6 6
2 8 2 8
1 4 1 4
EXAMPLE :
www.padeepz.n
www.padeepz.n
et
Case 2 :
6 6
2 8 2 8
1 4
1
3 3
www.padeepz.n
www.padeepz.n
et
Case 3 :
6 6
2 8 3 8
1 4 1 4
5
3 5
www.padeepz.n
www.padeepz.n
et
EXAMPLE
www.padeepz.n
www.padeepz.n
et
this is appropriate. It is easy to remove this inefficiency, by writing a special
delete_min function, and we have left it in only for simplicity.
www.padeepz.n
www.padeepz.n
T=T-->right;
et
Else if(T-->right==NULL)
T=T-->left;
Free(tmpcell);
}
Return T;
}
Introduction
To count the number of nodes in a given binary tree, the tree is required to
be traversed recursively until a leaf node is encountered. When a leaf node is
encountered, a count of 1 is returned to its previous activation (which is an
activation for its parent), which takes the count returned from both the
children's activation, adds 1 to it, and returns this value to the activation of
its parent. This way, when the activation for the root of the tree returns, it
returns the count of the total number of the nodes in the tree.
Program
#include <stdio.h>
#include <stdlib.h>
struct tnode
{
int data;
struct tnode *lchild, *rchild;
};
int count(struct tnode *p)
{
if( p == NULL)
return(0);
else
www.padeepz.n
www.padeepz.n
if( p->lchild == NULL && p->rchild == NULL)
et
return(1);
else
return(1 + (count(p->lchild) + count(p->rchild)));
www.padeepz.n
www.padeepz.n
*inserts the newly created node
et
as left child*/
temp2 = temp2->lchild;
if(temp2 == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
else
{
temp2->rchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the
newly created node
as left child*/
temp2 = temp2->rchild;
if(temp2 == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
}
return(p);
}
/* a function to binary tree in inorder */
void inorder(struct tnode *p)
{
if(p != NULL)
{
inorder(p->lchild);
printf("%d\t",p->data);
inorder(p->rchild);
}
}
www.padeepz.n
www.padeepz.n
void main()
et
{
struct tnode *root = NULL;
int n,x;
printf("Enter the number of nodes\n");
scanf("%d",&n);
while( n --- > 0)
{
printf("Enter the data value\n");
scanf("%d",&x);
root = insert(root,x);
}
inorder(root);
printf("\nThe number of nodes in tree are :%d\n",count(root));
}
Explanation
Input:
o 1.The number of nodes that the tree to be created should have
2. The data values of each node in the tree to be created
Output:
o The data value of the nodes of the tree in inorder
2. The count of number of node in a tree.
Example
Input:
o 1.The number of nodes the created tree should have = 5
2. The data values of nodes in the tree to be created are: 10, 20, 5,
9, 8
Output: 1. 5 8 9 10 20
2. The number of nodes in the tree is 5
Introduction
www.padeepz.n
www.padeepz.n
et
An elegant method of swapping the left and right subtrees of a given binary
tree makes use of a recursive algorithm, which recursively swaps the left and
right subtrees, starting from the root.
Program
#include <stdio.h>
#include <stdlib.h>
struct tnode
{
int data;
struct tnode *lchild, *rchild;
};
www.padeepz.n
www.padeepz.n
else
et
temp1 = temp1->rchild;
}
if( temp2->data > val)
{
temp2->lchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the
newly created node
as left child*/
temp2 = temp2->lchild;
if(temp2 == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
else
{
temp2->rchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the
newly created node
as left child*/
temp2 = temp2->rchild;
if(temp2 == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
}
return(p);
}
/* a function to binary tree in inorder */
void inorder(struct tnode *p)
{
if(p != NULL)
www.padeepz.n
www.padeepz.n
{
et
inorder(p->lchild);
printf("%d\t",p->data);
inorder(p->rchild);
}
}
struct tnode *swaptree(struct tnode *p)
{
struct tnode *temp1=NULL, *temp2=NULL;
if( p != NULL)
{ temp1= swaptree(p->lchild);
temp2 = swaptree(p->rchild);
p->rchild = temp1;
p->lchild = temp2;
}
return(p);
}
void main()
{
struct tnode *root = NULL;
int n,x;
printf("Enter the number of nodes\n");
scanf("%d",&n);
while( n - > 0)
{
printf("Enter the data value\n");
scanf("%d",&x);
root = insert(root,x);
}
printf("The created tree is :\n");
inorder(root);
printf("The tree after swapping is :\n");
root = swaptree(root);
inorder(root);
printf("\nThe original tree is \n");
root = swaptree(root);
inorder(root);
}
www.padeepz.n
www.padeepz.n
Explanation
et
Input:
o 1.The number of nodes that the tree to be created should have
2. The data values of each node in the tree to be created
Output:
o 1.The data value of the nodes of the tree in inorder
before interchanging the left and right subtrees
2. The data value of the nodes of the tree in inorder after
interchanging the left and right subtrees
Example
Input:
o 1.The number of nodes that the created tree should have = 5
2. The data values of the nodes in tree to be created are: 10, 20, 5,
9, 8
Output:
o 1. 5 8 9 10 20
2. 20 10 9 8 5
www.padeepz.n
www.padeepz.n
et
Applications of Trees
1. Compiler Design.
2. Unix / Linux.
3. Database Management.
4. Trees are very important data structures in computing.
5. They are suitable for:
a. Hierarchical structure representation, e.g.,
i. File directory.
ii. Organizational structure of an institution.
iii. Class inheritance tree.
b. Problem representation, e.g.,
i. Expression tree.
ii. Decision tree.
c. Efficient algorithmic solutions, e.g.,
i. Search trees.
ii. Efficient priority queues via heaps.
AVL TREE
The AVL tree is named after its two inventors, G.M. Adelson-Velsky and E.M.
Landis, who published it in their 1962 paper "An algorithm for the
organization of information."
Avl tree is a self-balancing binary search tree. In an AVL tree, the heights of
the two child subtrees of any node differ by at most one; therefore, it is also
said to be height-balanced.
The balance factor of a node is the height of its right subtree minus
the height of its left subtree and a node with balance factor 1, 0, or -1 is
considered balanced. A node with any other balance factor is considered
unbalanced and requires rebalancing the tree. This can be done by avl tree
rotations
www.padeepz.n
www.padeepz.n
Need for AVL tree
et
The disadvantage of a binary search tree is that its height can be as large
as N-1
This means that the time needed to perform insertion and deletion and
many other operations can be O(N) in the worst case
We want a tree with small height
A binary tree with N node has height at least Q(log N)
Thus, our goal is to keep the height of a binary search tree O(log N)
Such trees are called balanced binary search trees. Examples are AVL
tree, red-black tree.
An AVL tree is a special type of binary tree that is always "partially" balanced.
The criteria that is used to determine the "level" of "balanced-ness" which is
the difference between the heights of subtrees of a root in the tree. The
"height" of tree is the "number of levels" in the tree. The height of a tree is
defined as follows:
www.padeepz.n
www.padeepz.n
et
The height of an internal node is the maximum height of its children plus 1.
AVL trees are identical to standard binary search trees except that for every
node in an AVL tree, the height of the left and right subtrees can differ by at
most 1 . AVL trees are HB-k trees (height balanced trees of order k) of order
HB-1. The following is the height differential formula:
|Height (Tl)-Height(Tr)|<=k
When storing an AVL tree, a field must be added to each node with one of
three values: 1, 0, or -1. A value of 1 in this field means that the left subtree
has a height one more than the right subtree. A value of -1 denotes the
opposite. A value of 0 indicates that the heights of both subtrees are the
same. EXAMPLE FOR HEIGHT OF AVL TREE
Rotation :
www.padeepz.n
www.padeepz.n
Modification to the tree. i.e. , If the AVL tree is
et
Imbalanced, proper
rotations has to be done.
A rotation is a process of switching children and parents among two or
three adjacent nodes to restore balance to a tree.
Balance Factor :
BF= --1
7
5 12
BF=1 BF= --1
2 10 14
-> RL ( Right -- Left rotation) --- Do single Right, then single Left.
-> LR ( Left -- Right rotation) --- Do single Left, then single Right.
1. LL Rotation :
www.padeepz.n
www.padeepz.n
et
2. RR Rotation :
www.padeepz.n
www.padeepz.n
et
www.padeepz.n
www.padeepz.n
et
www.padeepz.n
www.padeepz.n
et
EXAMPLE:
LET US CONSIDER INSERTING OF NODES 20,10,40,50,90,30,60,70 in an AVL
TREE
www.padeepz.n
www.padeepz.n
et
www.padeepz.n
www.padeepz.n
et
www.padeepz.n
www.padeepz.n
et
www.padeepz.n
www.padeepz.n
et
AVL TREE ROUTINES
Struct avlnode
Typedef struct avlnode *position;
Typedef structavlnode *avltree;
Typedef int elementtype;
Struct avlnode
{
Elementtype element;
Avltree left;
Avltree right;
Int height;
};
Static int height(position P)
{ If(P==NUL
L)
return -1;
else
return P-->height;
}
Avltree insert(elementtype X, avltree T)
{ If(T==NUL
L)
{ / * Create and return a one node
tree*/ T= malloc(sizeof(structavlnode));
If(T==NULL)
Fatalerror(“Out of Space”);
Else
{
T-->element=X;
www.padeepz.n
www.padeepz.n
T-->height=0;
et
T-->left=T-->right=NULL;
}
}
Else if(X<T-->element)
{
T-->left=Insert(X,T-->left);
If(height(T-->left) - height(T-->right)==2)
If(X<T-->left-->element)
T=singlerotatewithleft(T);
Else
T=doublerotatewithleft(T);
}
Else if(X>T-->element)
{
T-->right=insert(X,T-->right);
If(height(T-->left) - height(T-->right)==2)
If(X>T-->right-->element)
T= singlerotatewithright(T);
Else
T= doublerotatewithright(T);
}
T-->height=max(height(T-->left),height(T-->right)) + 1;
Return T;
}
www.padeepz.n
www.padeepz.n
{
et
Position k1;
k1=k2-->left;
k2-->left=k1-->right;
k1-->right=k2;
k2-->height= max(height(k2-->left),height(k2-->right)) + 1;
k1-->height= max(height(k1-->left),height(k1-->right)) + 1;
return k1; / * New Root * /
}
www.padeepz.n
www.padeepz.n
et
Double rotation with Right :
PROBLEMS
APPLICATIONS
AVL trees play an important role in most computer related applications. The
need and use of avl trees are increasing day by day. their efficiency and less
complexity add value to their reputation. Some of the applications are
AVL trees guarantee that the difference in height of any two subtrees
rooted at the same node will be at most one. This guarantees an
asymptotic running time of O(log(n)) as opposed to O(n) in the case of a
standard bst.
Height of an AVL tree with n nodes is always very close to the
theoretical minimum.
Since the avl tree is height balabced the operation like insertion and
deletion have low time complexity.
www.padeepz.n
www.padeepz.n
et
Since tree is always height balanced.Recursive implementation is
possible.
The height of left and the right sub-trees should differ by atmost
1.Rotations are possible.
BINARY HEAPS
it is empty or
the key in the root is larger than that in either child and both subtrees
have the heap property.
Structure Property :
COMPLETE TREE
A binary tree is completely full if it is of height, h, and has 2h+1-1 nodes.
it is empty or
its left subtree is complete of height h-1 and its right subtree is
completely full of height h-2 or
www.padeepz.n
www.padeepz.n
et
its left subtree is completely full of height h-1 and its right subtree is
complete of height h-1.
PROCEDURE
INSERTION:
DELETION:
www.padeepz.n
www.padeepz.n
The deletion takes place by removing the root node.
et
The root node is then replaced by the last leaf node in the tree to obtain
the complete binary tree.
It is verified with its children and adjacent node for its heap property.
The verification process is carried downwards until the heap property
is satisfied.
If any verification is not satisfied then swapping takes place.
Then finally we have the heap.
PRIORITY QUEUE
Deletion(h) I Insertion(h)
PRIORITY
QUEUE
www.padeepz.n
www.padeepz.n
Linked List :
et
A simple linked list implementation of priority queue requires o(1) time
to perform the insertion at the front and o(n) to delete at minimum element.
1. Structure Property :
The Heap should be a complete binary tree, which is a completely filled
tree, which is a completely filled binary tree with the possible exception of the
bottom level, which is filled from left to right.
A Complete Binary tree of height H, has between 2h and (2h+1 - 1) nodes.
Sentinel Value :
The zeroth element is called the sentinel value. It is not a node of the
tree. This value is required because while addition of new node, certain
operations are performed in a loop and to terminate the loop, sentinel value is
used.
Index 0 is the sentinel value. It stores irrelated value, inorder to terminate the
program in case of complex codings.
Structure Property : Always index 1 should be starting position.
www.padeepz.n
www.padeepz.n
Mintree:
et
Parent should have lesser value than children.
Maxtree:
Parent should have greater value than children.
properties Max-heap
Min-heap
Min-heap:
The smallest element is always in the root node.Each node must have a
key that is less or equal to the key of each of its children.
Examples
Max-Heap:
The largest Element is always in the root node.
www.padeepz.n
www.padeepz.n
et
Each node must have a key that is greater or equal to the key of each of its
children.
Examples
HEAP OPERATIONS:
There are 2 operations of heap
Insertion
Deletion
2.12.1 Insert:
Adding a new key to the heap
www.padeepz.n
www.padeepz.n
et
To insert an element X, into the heap, do the following:
Step1: Create a hole in the next available location , since otherwise the
tree will not be complete.
Step2: If X can be placed in the hole, without violating heap order, then do
insertion, otherwise slide the element that is in the hole’s parent node, into
the hole, thus, bubbling the hole up towards the root.
Step3: Continue this process until X can be placed in the hole.
Example Problem :
www.padeepz.n
www.padeepz.n
et
2. Insert the keys 4, 6, 10, 20, and 8 in this order in an originally empty
max- heap
www.padeepz.n
www.padeepz.n
et
Removing the root node of a max- or min-heap, respectively
www.padeepz.n
www.padeepz.n
et
EXAMPLE PROBLEMS :
1. DELETE MIN
www.padeepz.n
www.padeepz.n
2. Delete Min -- 13
et
www.padeepz.n
www.padeepz.n
elementtype *element;
et
};
Insert Routine
www.padeepz.n
www.padeepz.n
For(i=++H-->size;H-->elements[i/2]>X;i=i/2)
et
H-->elements[i]=H-->elements[i/2];
H-->elements[i]=X;
}
Delete Routine
Elementtype deletemin(priorityqueue H)
{
int i,child;
elementtype minelement,lastelement;
if(isempty(H))
{
Error(“Priority queue is empty”);
Return H-->element[0];
}
Minelement=H-->element[1];
Lastelement=H-->element[H-->size--];
For(i=1;i*2<=H-->size;i=child)
{
/ *Find smaller child */
Child=i*2;
If(child!=H-->size && H-->elements[child++]<H-->elements[child])
{
Child++;
}
/ * Percolate one level * /
If(lastelement>H-->elements[child])
H-->element[i]=H-->elements[child];
Else
Break;
}
H-->element[i]=lastelement;
www.padeepz.n
www.padeepz.n
Return minelement;
et
}
1. Decrease Key.
2. Increase Key.
3. Delete.
4. Build Heap.
1. Decrease Key :
10 10 8
15 12 8 12 10 12
20 30 20 30 20 30
2. Increase Key :
10 10 10
12 22 12
15 20 12
20 30 20 30
www.padeepz.n
www.padeepz.n
22 30
et
www.padeepz.n
www.padeepz.n
et
3. Delete :
The delete(P,H) operation removes the node at the position P, from the heap
H. This can be done by,
12
20 - ∞ 12
10 12
22 30
22 30
22 30
Step 2 : Deletemin(H)
10 10
12 12
10
22 12
20 20
30
APPLICATIONS
www.padeepz.n
www.padeepz.n
Graph algorithms
et
Heap sort :
One of the best sorting methods being in-place and with no
quadratic worst-case scenarios.
Selection algorithms:
Finding the min, max, both the min and max, median, or even the k-th
largest element can be done in linear time using heaps.
Graph algorithms:
By using heaps as internal traversal data structures, run time will be
reduced by an order of polynomial. Examples of such problems are Prim's
minimal spanning tree algorithm and Dijkstra's shortest path problem.
ADVANTAGE
It is used in
o Heap sort
o Selection algorithms
o Graph algorithms
DISADVANTAGE
fety
maintenance
performance
Performance :
Allocating heap memory usually involves a long negotiation with the OS.
www.padeepz.n
www.padeepz.n
Maintenance:
et
Dynamic allocation may fail; extra code to handle such exception is
required.
Safety :
Object may be deleted more than once or not deleted at all .
B-TREES
Multi-way Tree
www.padeepz.n
www.padeepz.n
et
A B-tree of order m (or branching factor m), where m > 2, is either an empty
tree or a multiway search tree with the following properties:
The root is either a leaf or it has at least two non-empty
subtrees and at most m non-empty subtrees.
Each non-leaf node, other than the root, has at least m/2 non-
empty subtrees and at most m non-empty subtrees. (Note: x is the
lowest integer > x ).
The number of keys in each non-leaf node is one less than the
number of non-empty subtrees for that node.
All leaf nodes are at the same level; that is the tree is perfectly
balanced.
www.padeepz.n
www.padeepz.n
et
Insertion in B-Trees
OVERFLOW CONDITION:
A root-node or a non-root node of a B-tree of order m overflows if, after a
key insertion, it contains m keys.
Insertion algorithm:
If a node overflows, split it into two, propagate the "middle" key to the
parent of the node. If the parent overflows the process propagates upward. If
the node has no parent, create a new root node.
• Note: Insertion of a key always starts at a leaf node.
www.padeepz.n
www.padeepz.n
et
Example: Insert the keys 78, 52, 81, 40, 33, 90, 85, 20, and 38 in this order in
an initially empty B-tree of order 3
www.padeepz.n
gate
www.padeepz.n
questions
et
and answers
Binary Trees
1. Construct a binary tree whose preorder traversal is K L N M P R Q S T and in order traversal is N L K P R M S Q T
2. (i) Define the height of a binary tree or subtree and also define a height balanced (AVL) tree.
The height of a tree or a sub tree is defined as the length of the longest path from the root node to the leaf.
A tree is said to be height balanced if all the nodes are having a balance factor -1,0 or 1. The balance factor is the height of the left
sub tree minus height of the right sub tree
(ii) Mark the balance factor of each mode on the tree given in fig 7.1 and state whether it is height-balanced
(iii) Into the same tree given in 7(ii) above, insert the integer 13 and show the new balance factors that would arise if the tree
is no rebalanced. Finally, carry the required rebalancing of the tree and show the new tree with the balance factors on each mode.
www.padeepz.n
www.padeepz.n
et
………
………
www.padeepz.n
www.padeepz.n
4. 1
et
Consider the height balanced tree T , with values stored at only the leaf nodes, shown in Fig. 4
Fig 4
(i)
Show how to merge to the tree T1 elements from tree T2 shown in Fig. 5 using node D of tree T1
Fig 5
(ii)
What is the time complexity of a merge operation on balanced trees T1 and T2 where T1 and T2 are of height h1 and h2
respectively, assuming rotation scheme are given. Give reasons
5. The number of different ordered trees with 3 nodes labeled Y, Y, Z are
(A) 16
(B) 8
(C) 12
(D) 24
Ans: 15
However, we want to order the nodes based on Y, Y and Z, there are 3 possibilities associated with every tree structure.
Hence, 5 * 3 = 15
6. Construct a binary tree whose preorder and inorder sequences are A B M H E O C P G J D K L I N F and H M C O E B A G P K L
www.padeepz.n
www.padeepz.n
et
D I N J F respectively, where A, B, C, D, E,...............are the labels of the tree nodes. Is it unique?
(a) (b)
(c) (d)
www.padeepz.n
www.padeepz.n
et
(e)
Fig 2
weighted external path = (2*4) + (4*4) + (5*4) + (7*4) + (9*3) + (10*3) + (15*1)
= 8 + 16 + 20 + 28 + 27 + 30 + 15
=144
8. If the binary tree in Fig. 3 is traversed in inorder, then the order in which the nodes will be visited is
www.padeepz.n
www.padeepz.n
et
Fig 3
41673258
Fig. 7
(a)Min-Heap
(b)
i. Swap(27,5)
ii. Delete 5
iii. Minheapify
(c)
Alogithm delMinHeap()
www.padeepz.n
www.padeepz.n
Step 2: copy last element to this location
et
Step 3: remove last element of array
Algorithm Min-Heapify()
Then smallest=2i
Else smallest =i
Then smallest=2i+1
Step3: If smallest != i
Step 3: Min-Heapify(A,smallest)
10. if a tree has n1 nodes of degree 1, n2 nodes of degree 2, …. nm nodes of degree m, give a formula for the number of terminal nodes
n0 of the tree in terms of n1, n2, …., nm.
(A) 4
(B) 5
(C) 6
(D) 7
A and D
At leaf-level:
www.padeepz.n
www.padeepz.n
1. group the nodes into 3 sets of 3 …… it gives 4 internal nodes
et
2. group the nodes into 3 sets of 2 and 1 set of 3 …… it gives 7 internal nodes
12. A K-ary tree is such that every node has either K sons or no sons. If L and I are the number of leaves and internal nodes
respectively, then express L in terms of K and I.
If there is only one 1 internal node then it have k leaf nodes.
Adding one more internal node means making 1 leaf node as internal and adding k leaf nodes.
L=K*(I-1)+1
13. A 3-ary tree is a tree in which every internal node has exactly three children. Use the induction to prove that the number of leaves
in a 3-ary tree with n internal nodes is 2(n-1) + 3.
When,
n = 0 l = 2(0 - 1) + 3 =1
n = 1 l = 2(1 - 1) + 3 = 3
Hence l = 2(k - 1) + 3
For n = k + 1
= 2k + 3
= 2((k + 1)-1) + 3
(a) x (n – 1) + 1 (b) xn – 1
(c) xn + 1 (d) x (n + 1)
[A]
Degree of root = n
Also,
But n = x + L
www.padeepz.n
www.padeepz.n
Thus, no. of edges = x + L -1
et
(n + 1) * (x - 1) + n + L = x + L -1
Ans: L = x(n - 1) + 1
15.
16. The minimum number of interchanges needed to convert the array
(A) 0 (B) 1
(C) 2 (D) 3
Only element 70 violates the rule. Hence, it must be shifted to its proper position.
(A) that support recursion (B) that support dynamic data structures
(C) that use dynamic scope rules (D) none of the above
[B] Dynamic data structures have the capacity to grow. Hence, they need some sort of memory
allocation during runtime. The heap is required to provide this memory.
18. A binary tree T has n leaf nodes. The number of nodes of degree 2 in T is
(a)
log2n
(b)
n-1
(c)
n
(d)
2n
[B] Total no. of nodes in the tree
n = n0 + n1 + n2
www.padeepz.n
www.padeepz.n
Where ni is the number of nodes with i children.
et
But e = n ‐ 1
n1 + 2*n2 = n0 + n1 + n2 – 1
n2 = n0 – 1
n2 = n ‐ 1
19. What is the number of binary trees with 3 nodes which when traversed in post-order give the sequence A, B, C? Draw all these
binary trees.
Ans: 5
20. In the balanced binary tree in Fig. 1.14 given below, how many nodes will become unbalanced when a node is inserted as a child of
the node “g”?
Fig. 1.14
(A) 1
(B) 3
(C) 7
(D) 8
[B]
After insertion
Bf(a) = 2
www.padeepz.n
www.padeepz.n
Bf(b) = 2
et
Bf(c) = 2
Bf(d) = 0
Bf(e) = 1
Bf(f) = 0
Bf(g) = 1
Which of the following sequences denotes the post-order traversal sequence of the tree of FIG 1.14?
(A) f e g c d b a (B) g c b d a f e
(C) g c d b f e a (D) f e d g c b a
[C]
Post-order = Left sub-tree – right sub-tree – self
21. A binary search tree is generated by inserting in order the following integers:
The number of nodes in the left subtree and right subtree of the root is respectively
[B]
Nodes to in the left subtree are less than 50, while nodes in the right sub-tree are greater than 50.
(A) 61 52 14 17 40 43
(B) 2 3 50 40 60 43
(C) 10 65 31 48 37 43
(D) 81 61 52 14 41 43
(E) 17 77 27 66 18 43
Possible:[ A,C, D]
Not possible:
[B] – at 50 the left branch is taken. Hence, all nodes in the list after 50 must be less than it. But 60 is not similarly in[ D]18 is
smaller than 27
23. A binary search tree contains the values 1, 2, 3, 4, 5, 6, 7, 8. The tree is traversed in pre-order and the values are printed out.
Which of the following sequences is a valid output?
www.padeepz.n
www.padeepz.n
(A) 5 3 1 2 4 7 8 6
et
(B) 5 3 1 2 6 4 8 7
(C) 5 3 2 4 1 6 7 8 (D) 5 3 1 2 4 7 6 8
Valid: d
Invalid: a, b,
(a) Prove, by using induction on h, that a size-balanced binary tree of height h contains at least 2h nodes.
When
nodes
If we increase the height by 1 by adding a node, we must also add nodes to fill the (max level -1) level.
Thus 2^ (k+1)
Hence, proved
(b) In a size-balanced binary tree of height h ≥ 1, how many nodes are at distance h-1 from the root? Write only the answer
without any explanation
2 h-1
25. Suppose the numbers 7, 5, 1, 8, 3, 6, 0, 9, 4, 2 are inserted in that order into an initially empty binary search tree. the binary
search tree uses the usual ordering on natural numbers. What is the inorder traversal sequence of the resultant tree?
(A) 7510324689
(B) 0243165987
(C) 0123456789
(D) 9864230157
[C] In order traversal of the binary search tree is always in ascending order
www.padeepz.n
www.padeepz.n
26. Which of the following statements is false?
et
(a) A tree with n nodes has (n-1) edges
(b) A labeled rooted binary tree can be uniquely constructed given its post-order and pre-order traversal results.
(c) A complete binary tree with n internal nodes has (n+1) leaves
(d) The maximum number of nodes in a binary tree of height h is (2h+1 – 1)
[B and D] With inorder,preorder or with inorder, postorder it is possible for a unique combination
27. Draw the binary tree with the node labels a, b, c, d, e, f and g for which the inorder and post-order traversals result in the following
sequences
Inorder afbcdge
Postorder afcgedb
28. Draw the min-heap that results from insertion of the following elements in order into an initially empty min-heap: 7, 6, 5, 4, 2, 3,
1. show the result after the deletion of the root of this heap.
www.padeepz.n
www.padeepz.n
et
(d) (e)
29. The number of leaf nodes in a rooted tree of n node, with each node having 0 or 3 children is:
A. n/2
B. (n – 1)/3
C. (n – 1)/2
D. (2n + 1)/3
[D]Degree of internal node (except root node) = 4
Degree of root = 3 or 0
No of edges = n – 1
Case 2:
(n – L - 1) * 4 + 3 + L * 1 = 2 * (n - 1)
…………………………..
www.padeepz.n
www.padeepz.n
………………………….
et
N full nodes have N+1 leaves
31. Consider the following nested representation of binary trees: (X Y Z) indicates Y Z are the left and right subtrees, respectively, of
node X. Note that Y and Z may be NULL, or further nested. Which of the following represents a valid binary tree?
(A) (1 2 (4 5 6 7))
(B) (1 ( ( 2 3 4) 5 6) 7)
(C) (1 (2 3 4) (5 6 7))
(D) (1 (2 3 NULL) (4 5))
[C] Every node contains two sub trees.
32. Let LASTPOST, LASTIN and LASTPRE denotes the last vertex visited in a post-order, inorder and pre-order traversal
respectively, of a completely binary tree. Which of the following is always true?
In-order = LNR
Pre-order = NLR
Post-order = LRN
The rightmost element will be the last element in both in and pre orders
33. (a) Insert the following keys one by one into a binary search tree in order specified.
www.padeepz.n
www.padeepz.n
et
(b) Draw the binary search tree after deleting 15 from it.
(c) Complete the statements S1, S2 and S3 in the following function so that the function computes the depth of a binary tree
rooted at t.
typedef struct tnode {
int key;
} *Tree;
www.padeepz.n
www.padeepz.n
{
et
int x,y;
if (t = = NULL) return 0;
x = depth(t →left);
S1: ;
S1: y=depth(t->right)
S2: x+1
S3: y+1
34. A weight balanced tree is a binary tree in which for each node, the number of nodes in the left subtree is at least half and at most
twice the number of nodes in the right subtree. The maximum possible height (number of nodes on the path from the root to the
furthest leaf) of such a tree on n nodes is best described by which of the following?:
A.
log2n
B.
log4/3 n
C.
log3n
D.
log3/2 n
35. Draw all binary trees having exactly three nodes labeled A, B, and C on which pre-order traversal gives the sequence C, B, A.
Ans: 5
As a heap may contain duplicate values, we may need to remove more then 7 elements. At the worst case we will have to remove
all n elements.
www.padeepz.n
www.padeepz.n
et
38. (i) Define the height of a binary tree or subtree and also define a height balanced (AVL) tree.
The height of a tree or a sub tree is defined as the length of the longest path from the root node to the leaf.
A tree is said to be height balanced if all the nodes are having a balance factor -1,0 or 1. The balance factor is the height of the left
sub tree minus height of the right sub tree
(ii) Mark the balance factor of each mode on the tree given in fig 7.1 and state whether it is height-balanced
(iii) Into the same tree given in 7(ii) above, insert the integer 13 and show the new balance factors that would arise if the tree
is no rebalanced. Finally, carry the required rebalancing of the tree and show the new tree with the balance factors on each mode.
www.padeepz.n
www.padeepz.n
et
N=1 1 tree
N=2 2 trees
N=3 5 trees
N=4 14 trees
www.padeepz.n
www.padeepz.n
40. The maximum number of nodes in a binary tree of level k, k ≥ 1 is
et
(E) 2k + 1
(F) 2k - 1
(G) 2k-1
(H) 2k-1 - 1
41. Construct a binary tree whose preorder and inorder sequences are A B M H E O C P G J D K L I N F and H M C O E B A G P K
L D I N J F respectively, where A, B, C, D, E,...........are the labels of the tree nodes. Is it unique?
(a) (b)
(c) (d)
www.padeepz.n
www.padeepz.n
et
(e)
Fig 2
weighted external path = (2*4) + (4*4) + (5*4) + (7*4) + (9*3) + (10*3) + (15*1)
= 8 + 16 + 20 + 28 + 27 + 30 + 15
=144
44. If the binary tree in Fig. 3 is traversed in inorder, then the order in which the nodes will be visited is
www.padeepz.n
www.padeepz.n
et
Fig 3
In-order traversal: 4 1 6 7 3 2 5 8
Fig. 7
(a)Min-Heap
(b)
iv. Swap(27,5)
v. Delete 5
vi. Minheapify
(c)
Alogithm delMinHeap()
location
www.padeepz.n
www.padeepz.n
Step 3: remove last element of array
et
Step 4: perform Min-Heapify on I th node
Algorithm Min-Heapify()
Then smallest=2i
Else smallest =i
Then smallest=2i+1
Step3: If smallest != i
Step 3: Min-Heapify(A,smallest)
46. Consider a binary max-heap implemented using an array.
www.padeepz.n
www.padeepz.n
et
(d) (e)
47. What is the maximum height of any AVL-tree with 7 nodes? Assume that the height of a tree with a single node is 0.
By substituting n=7 we get 4.03,since it is given that the height of a tree with a single node is 0.Therefore the answer is 3.
48. The following three are known to be the preorder, inorder and postorder sequences of a binary tree. But it is not known which is
which.
I. MBCAFHPYK
II. KAMCBYPFH
III. MABCKYFPH
Pick the true statement from the following.
www.padeepz.n
www.padeepz.n
K occurs as the first element tin II. Thus, II must be pre-order.
et
Thus, III must be in-order.
49. Which of the following is TRUE?
(A) The cost of searching an AVL tree is (log n) but that of a binary search tree is O(n)
(B) The cost of searching an AVL tree is (log n) but that of a complete binary tree is (n log n)
(C) The cost of searching a binary search tree is O(log n) but that of an AVL tree is (n)
(D) The cost of searching an AVL tree is (n log n) but that of a binary search tree is O(n)
[A]Searching in AVL tree has O(logn) complexity.
And searching for binary search tree is also O(n), when it is skewed and is order of O(log(n)) when it is complete
50. We have a binary heap on n elements and wish to insert n more elements (not necessarily one after another) into this heap. The
total time required for this is
(A) (log n)
(B) (n)
(C) (n log n)
(D) (n2 )
[C]
(A) (log n)
(B) (n)
(C) (n log n)
(D) none of the above, as the tree cannot be uniquely determined.
[C] To get unique tree we must have pre order and in order or post order and inorder.
In order traversal of a BST is always sorted.
I=Sort P( using merge sort or heap sort which takes O(nlogn) )
Using I and P construct the tree.
52. When searching for the key value 60 in a binary search tree, nodes containing the key values 10, 20, 40, 50, 70, 80, 90 are
traversed, not necessarily in the order given. How many different orders are possible in which these key values can occur on the
search path from the root node containing the value 60?
53. Consider the process of inserting an element into a Max Heap, where the Max Heap is represented by an array. Suppose we
perform a binary search on the path from the new leaf to the root to find the position for the newly inserted element, the number of
comparisons performed is:
(A)
Θ(log2 n)
(B)
Θ(log2 log2 n)
(C)
Θ(n)
(D)
Θ(n log2 n)
[B]
n = no of elements in the tree.
www.padeepz.n
www.padeepz.n
lgn = height of the tree i.e. path length of the newly inserted node to the root.
et
Complexity of binary search = O(lgn) where n is the no. of elements searched.
Thus, O(ln(lg(n)))
54. A complete n-ary tree is a tree in which each node has n children or no children. Let I be the number of internal nodes and L be the
number of leaves in a complete n-ary tree. if L = 41, and I = 10, what is the value of n?
L = I(n - 1) + 1
Thus n = (L - 1) / I – 1
i.e n = (41 - 1) / 10 -1
Ans: n = 3
d b e a f c g and a b d e c f g, respectively.
(A) debfgca
(B) edbgfca
(C) edbfgca
(D) defgbca
[A]
(a) (b)
56. The maximum number of binary trees that can be formed with three unlabeled nodes is:
[B] Using formula (1/(n+1) )* 2nCn , where n is the number of unlabeled node so 5
57. The height of a binary tree is the maximum number of edges in any root to leaf path. The maximum number of nodes in a binary
tree of height h is:
Level 0: h = 0; nodes = 1
www.padeepz.n
www.padeepz.n
Level 1: h = 1; nodes = 2
et
Level 2: h = 2; nodes = 4
(A) {10, 75, 64, 43, 60, 57, 55} (B) {90, 12, 68, 34, 62, 45, 55}
(C) {9, 85, 47, 68, 43, 57, 55} (D) {79, 14, 72, 56, 16, 53, 55}
[C] On arriving at node 47, we take the right sub-tree. The right sub-tree can contain only those nodes which are larger than 47. But
43 < 47
(A) {23, 17, 14, 6, 13, 10, 1, 12, 7, 5} (B) {23, 17, 14, 6, 13, 10, 1, 5, 7, 12}
(C) {23, 17, 14, 7, 13, 10, 1, 5, 6, 12} (D) {23, 17, 14, 7, 13, 10, 1, 12, 5, 7}
[C] In a max heap parent node is always greater than its children. Only [C] satisfies this property
60. A scheme for sorting binary trees in an array X is as follows. Indexing of X starts at 1 instead of 0. The root is stored at X[1]. For a
node stored at X[i], the left child, if any is stored in X[2i] and the right child, if any, in X[2i + 1]. To be able to store any binary
tree on n vertices the minimum size of X should be
61. In a binary max heap containing n numbers, the smallest element can be found in time
[A]The smallest element can be found in last level of tree. So finding smallest we have to perform search in last level and that
search can be performed in O(n).So total complexity will be O(logn+n)= O(n).
62. A binary search tree contains the numbers 1, 2, 3, 4, 5, 6, 7, 8. When the tree is traversed in pre-order and the values in each node
printed out, the sequence of values obtained is 5, 3, 1, 2, 4, 6, 8, 7. If tree is traversed in post-order, the sequence obtained would be
(A) 8, 7, 6, 5, 4, 3, 2, 1
(B) 1, 2, 3, 4, 8, 7, 6, 5
(C) 2, 1, 4, 3, 6, 7, 8, 5
(D) 2, 1, 4, 3, 7, 8, 6, 5
[D]
www.padeepz.n
www.padeepz.n
et
N= h+[1/2*[(h-2)*(h-3)]]
64. The numbers 1, 2, …, n are inserted in a binary search tree in some order. In the resulting tree, the right subtree of the root contains
p nodes. The first number to be inserted in the tree must be
1 r n
r=n-p
65. In a complete k-ary tree, every internal node has exactly k children. The number of leaves in such a tree with n internal nodes is:
(A) nk
(B) (n-1)k +1
(C) n(k – 1) + 1
(D) n(k – 1)
[C]Degree of internal nodes (except root) = k + 1
Degree of root = k
Also,
www.padeepz.n
www.padeepz.n
Thus, no. of edges = n + L -1
et
(k + 1) * (n - 1) + k + L = n + L -1
Ans: L = n(k - 1) + 1
66. How many distinct binary search tree can be created out of 4 distinct keys?
(A) 5
(B) 14
(C) 24
(D) 42
1 2n
[B] By formula
(n 1) n
67. A Priority-Queue is implemented as a Max-Heap. Initially, it has 5 elements. The level-order traversal of the heap is given below:
10, 8, 5, 3, 2
Two new elements ‘1’ and ‘7’ are inserted in the heap in that order. The level-order traversal of the heap after the insertion of the
elements is:
(A) 10, 8, 7, 5, 3, 2, 1
(B) 10, 8, 7, 2, 3, 1, 5
(C) 10, 8, 7, 1, 2, 3, 5
(D) 10, 8, 7, 3, 2, 1, 5
[D]
(a) (b)
68. Which of the following binary trees has its inorder and preorder traversals as BCAD and ABCD, respectively?
www.padeepz.n
www.padeepz.n
et
(A)
B C
(B)
(C)
(D)
B D
69. An array of integers of size n can be converted into a heap by adjusting the heaps rooted at each internal node of the complete
binary tree starting at the node (n 1) / 2 , and doing this adjustment upto the root node (root node is at index 0) in the order
(n 1) / 2 , (n 3) / 2, …, 0. The time required to construct a heap in this manner is
(A) O(log n)
(B) O(n)
(C) O(n log log n)
(D) O(n log n)
www.padeepz.n
www.padeepz.n
[B] Refer Cormen for proof
et
70. A program takes as input a balance binary search tree with n leaf nodes and computes the value of a function g(x) for each node x.
if the cost of computing g(x) is min {no. of leaf nodes in left-subtree of x, no. of leaf-nodes in right-sub tree of x} then
the worst time case complexity of the program is
(A) Θ(n)
(B) Θ(n log n)
(C) Θ(n2)
(D) Θ(n2 log n)
[B] The recurrence relation for the recursive function is
= 4 * T(N/2) + 3(n/2)
Where i = lg(N)
= lg((2n - 1) / 2)
O((2*i - 1) * (n/2))
O(n * ln(n))
71. Consider the following C program segment
struct CellNode{
int element;.
};
www.padeepz.n
www.padeepz.n
int value = 0;
et
if(ptr != NULL)
The value returned by the function DoSomething when a pointer to the root of a non-empty tree is passed as argument is
72. The elements 32, 15, 20, 30, 12, 25, 16 are inserted one by one in the given order into a maxheap. The resultant max heap is
[A]
www.padeepz.n
www.padeepz.n
(a) (b) (c)
et
(d) (e)
73. Consider the label sequences obtained by the following pairs of traversals on a labeled binary tree. Which of these pairs identify a
tree uniquely?
(A) (i)only
(B) (i), (iii)
(C) (iii)only
(D) (iv)only
(ii) and (iii)
here [C] is also correct
74. Level order traversal of a rooted tree can be done by starting the root and performing
[D] A breath first search is implemented by enqueueing the root and the repeating the following-
Step: dequeue a node and push its children in the queue from the left to right.
75. The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 15, 12, 16. What is the height of
the binary search tree (the height is the maximum distance of a leaf node from the root)?
(A) 2
(B) 3
(C) 4
(D) 6
[A]
www.padeepz.n
www.padeepz.n
et
www.padeepz.n
www.padeepz.n
et
ADVANTAGES:
• B-trees are suitable for representing huge tables residing in
secondary memory because:
1. With a large branching factor m, the height of a B-tree is
low resulting in fewer disk accesses.
2. The branching factor can be chosen such that a node corresponds
to a block of secondary memory.
3. The most common data structure used for database indices is the
B- tree. An index is any data structure that takes as input a
property (e.g. a value for a specific field), called the search key, and
quickly finds all records with that property.
Note: As m increases the amount of computation at each node increases;
however this cost is negligible compared to hard-drive accesses.
www.padeepz.n
Unit IV: Graphs: DEFINITION-REPRESENTATION OF GRAPH-
w w w . padeepz.net
T YP ES O F GRAPH-BREADTH FIRST TRACERSAL-EPTH
FIRST TRAVERSAL -TOPOLOGICAL
SORT-BI-CONNECTIVITY-CUT VERTEX-EUCLER CIRCUITS-APPLICATIONS OF HEAP.
Application of graphs:
Coloring of MAPS
Representing network
o Paths in a city
o Telephone network o
Electrical circuits etc.
It is also using in social
network including o
LinkedIn
o Facebook
Types of Graphs:
Directed graph
Undirected Graph
Directed Graph:
In representing of graph there is a directions are
shown on the edges then that graph is called
Directed graph.
That is,
A graph G=(V, E) is a directed graph ,Edge is a
pair (v, w), where v, w ∈ V, and the pair is
ordered. Means vertex ‘w’ is adjacent to v.
Directed graph is also called digraph.
Undirected Graph:
In graph vertices are not ordered is called undirected
graph. Means in which (graph) there is no direction
(arrow head) on any line (edge).
A graph G=(V, E) is a directed graph ,Edge is a pair
www.padeepz.net
www.padeepz.net
Difference between Trees and
Graphs Graphs
Path Trees
Tree is special form of graph i.e. minimally In graph there can be more than
connected graph and having only one path one path i.e. graph can have uni-
between any two vertices. directional or bi-directional paths
(edges) between nodes
Loops Tree is a special case of graph having Graph can have loops, circuits as
no loops, no circuits and no self-loops. well as can have self-loops.
Root Node In tree there is exactly one root node In graph there is no such concept
and every child have only one parent. of root node.
Parent In trees, there is parent child relationship In Graph there is no such parent
Child so flow can be there with direction top to child relationship.
relationship bottom or vice versa.
Complexity Trees are less complex then graphs as Graphs are more complex in
having no cycles, no self-loops and still compare to trees as it can have
connected. cycles, loops etc
Types of Graph is traversed by
Traversal Tree traversal is a kind of special case of DFS: Depth First Search
traversal of graph. Tree is traversed in Pre- BFS : Breadth First Search
Order, In-Order and Post-Order(all algorithm
Connection three in DFS or in BFS algorithm) In graphs no such rules/
Rules In trees, there are many rules / restrictions restrictions are there for
for making connections between nodes connecting the nodes through
through edges. edges.
DAG Graph can be Cyclic or Acyclic.
Trees come in the category of DAG :
Directed Acyclic Graphs is a kind of
Different directed graph that have no cycles.
There are mainly two types of
Types Different types of trees are : Binary Tree Graphs :Directed and Undirected
, Binary Search Tree, AVL tree, Heaps. graphs.
Applications Graph applications : Coloring
Tree applications: sorting and searching of maps, in OR (PERT &
like Tree Traversal & Binary Search. CPM), algorithms, Graph
coloring, job scheduling, etc.
No. of edges In Graph, no. of edges depends on
Tree always has n-1 edges. the graph.
Model Tree is a hierarchical model. Graph is a network model.
Figure
www.padeepz.n
Other types of graphs:
www.padeepz.n
Complete Graph: et
A complete graph is a simple undirected graph in which every pair of distinct vertices is
connected by a unique edge.
OR
If an undirected graph of n vertices consists of n(n-1)/2 number of edges then the graph
is called complete graph.
Example:
vertices Edges Complete graph vertices Edges Complete graph
n=2 1 n=6 15
n=3 3 n=7 21
n=4 6 n=5 10
www.padeepz.n
Sub graph:
www.padeepz.n
et
A sub-graph G' of graph G is a graph, such that the set of vertices and set of edges
of G' are proper subset of the set of vertices and set of edges of graph G
respectively.
Connected Graph:
A graph which is connected in the sense of a topological space ( study of shapes), i.e., there
is a path from any point to any other point in the graph. A graph that is not connected is said to
be disconnected.
www.padeepz.n
Path:
www.padeepz.n
et
A path in a graph is a finite or infinite sequence of edges which connect a sequence of
vertices. Means a path form one vertices to another vertices in a graph is represented by
collection of all vertices (including source and destination) between those two vertices.
Simple Cycle: a cycle that does not pass through other vertices more than once
Degree:
The degree of a graph vertex v of a graph G is the number of graph edges which touch v.
The vertex degree is also called the local degree or valency. Or
The degree (or valence) of a vertex is the number of edge ends at that vertex.
For example, in this graph all of the vertices have degree three.
In a digraph (directed graph) the degree is usually divided into the in-degree and the out-
degree
In-degree: The in-degree of a vertex v is the number of edges with v as their
terminal vertex.
Out-degree: The out-degree of a vertex v is the number of edges with v as their
initial vertex.
www.padeepz.n
www.padeepz.n
et
TOPOLOGICAL SORT
A topological sort is a linear ordering of vertices in a Directed Acyclic
Graph such that if there is a path from Vi to Vp, then Vj appears after Vi in the
linear ordering.Topological sort is not possible if the graph has a cycle.
INTRODUCTION
PROCEDURE
Step – 3 : Dequeue the vertex V and decrement the indegrees of all its adjacent
vertices.
Step – 4 : Enqueue the vertex on the queue if its indegree falls to zero.
Vertices Indegree
1 0
2 0
www.padeepz.n
www.padeepz.n
et
GRAPH TRAVERSAL
Graph traversal is the Visiting all the nodes of a graph.
The Breadth first search was one of the systematic approaches for
exploring and searching the vertices/nodes in a given graph. The
approach is called "breadth-first" because from each vertex ‘v’ that we
visit, we search as broadly as possible by next visiting all the vertices
adjacent to v.
It can also be used to find out whether a node is reachable from a
given node or not.
It is applicable to both directed and undirected graphs.
Queue is used in the implementation of the breadth first search.
www.padeepz.n
www.padeepz.n
et
ALGORITHM
Procedure bfs()
{
//BFS uses Queue data structure
Queue q=new LinkedList();
q.add(this.rootNode);
printNode(this.rootNode);
rootNode.visited=true; while(!
q.isEmpty())
{
Node n=(Node)q.remove(); Node child=null;
while((child=getUnvisitedChildNode(n))!=null)
{
child.visited=true;
printNode(child);
q.add(child);
}
}
//Clear visited property of nodes
clearNodes();
}
Procedure
Step -1 Select the start vertex/source vertex. Visit the vertex and mark it
as one (1) (1 represents visited vertex).
Step -2 Enqueue the vertex.
Step -3 Dequeue the vertex.
Step -4 Find the Adjacent vertices.
Step -5 Visit the unvisited adjacent vertices and mark the distance as
1. Step -6 Enqueue the adjacent vertices.
Step -7 Repeat from Step – 3 to Step – 5 until the queue becomes empty.
www.padeepz.n
www.padeepz.n
et
Ex : A B Vertices Visited
Vertices
A 1
C D B 0 1
C 0 1
D 0 1
Enqueue A B C D
Dequeue A B C D
A B
Vertices Visited
Vertices
C 1
C D A 0 1
B 0 1
D 0 1
E E 0 1
Enqueue C A B D
E
Dequeue C A B D
E
Pseudo Code :
void BFS(Vertex S)
Vertex v,w;
Queue Q;
visited[s] = 1; enqueue(S,Q);
while(!IsEmpty(a))
www.padeepz.n
www.padeepz.n
et
v = Dequeue(Q);
print(v);
if(visited[w]==0)
visited[w] = 1;
Enqueue(w,Q);
APPLICATIONS
Breadth-first search can be used to solve many problems in graph theory, for
example.
Uses
www.padeepz.n
www.padeepz.n
et
Testing whether graph is connected.
Computing a spanning forest of graph.
Computing, for every vertex in graph, a path with the minimum number
of edges between start vertex and current vertex or reporting that no
such path exists.
Computing a cycle in graph or reporting that no such cycle exists.
www.padeepz.n
www.padeepz.n
et
This entire process is repeated until all vertices are discovered.
Stack is used in the implementation of the depth first search.
In DFS, the basic data structures for storing the adjacent nodes is stack.
Procedure:
A B Stack O/P
Vertices Visited
Vertices
A
A 1
C D B 0 1 DC
C 0 1
A D C B D 0 1
www.padeepz.n
www.padeepz.n
et
Pseudo Code:
void DFS(Vertex S)
int top = 0;
visited [S] = 1
C[top] = S; while(!
IsEmpty(C))
v = pop(C);
print(V);
if(visited[w] == 0)
visited[w] = 1;
push(w,C);
(OR)
www.padeepz.n
www.padeepz.n
et
void DFS(vertex V)
visited[v] = 1;
push(v);
pop(v);
if(!visited[w])
Dfs(w);
ALGORITHM
Procedure dfs()
{
//DFS uses Stack data structure
Stack s=new Stack();
s.push(this.rootNode);
rootNode.visited=true;
printNode(rootNode); while(!
s.isEmpty())
{
Node n=(Node)s.peek();
Node child=getUnvisitedChildNode(n);
if(child!=null)
{
child.visited=true;
printNode(child);
s.push(child);
}
else
{
s.pop();
www.padeepz.n
www.padeepz.n
}
et
}
//Clear visited property of nodes
clearNodes();
}
Applications of DFS :
I. Undirected Graph :
An undirected graph is connected if and only if a depth first search
starting from any node visits every node.
A
1. Tree Edge
2. Back Edge------------>
B D E
A A
C B B
C E C
D D
B A C
G B
C D A
www.padeepz.n
www.padeepz.n
et
F D
G E F
E
A
B
C D
G E
II. Bi-Connectivity :
B A A (1,1)
B (2,1)
C D (3,1) C G (7,7)
www.padeepz.n
www.padeepz.n
et
F D (4,1)
G E E (5,4)
F (6,4)
BICONNECTIVITY :
A connected undirected graph is biconnective if there are no vertices
whose removal disconnects the rest of the graph.
DEFINITION
Biconnected Components
www.padeepz.n
www.padeepz.n
et
Interaction of biconnected components
Articulation Point :
The root is an articulation if and only if (iff) it has more than two children.
Any vertex V other than the root is an Articulation point iff V has some child W
such that Low(W)≥Num (V)
A
(1,1)
B (2,1)
C (3,1)
D (4,1) G (7,7)
www.padeepz.n
www.padeepz.n
et
E (5,4)
F (6,4)
= min(6, 4, -1)
=4
Low(E) = min(5, 6, 4)
=4
Low(D) = min(4, 1, 4)
=1
Low(G) = min(7, -, -)
=7
=1
Low(B) = min(2, 3, 1)
=1
Low(A) = min(1, 2, 1)
=1
Example 2
B E H I
www.padeepz.n
www.padeepz.n
et
A C F I K
D
G
A F
D G E
I
Visited Parent[]
1 2 3 4
1 1 1 1 1 1 1 1
A B C D 0 1 2 3
0 1 2 3
1 1 1 1
Num[]
A B C D
A A (1,1)
B C B (2,1)
D C (3,1)
www.padeepz.n
www.padeepz.n
et
D (4,4)
ALGORITHM
void AssignNum(Vertex V)
{
Vertex W;
int counter = 0;
Num[V] = ++counter;
visited[V] = True;
for each W adjacent to V if(!
visited[W])
{
parent[W] = V;
AssignNum(W);
}
}
void AssignLow(Vertex V)
{
Vertex W;
Low[V] = Num[V]; /* Rule 1 */
for each W adjacent to V
{
if(Num[W] > Num[V]) /* forward edge or free edge */
{ AssignLow(W)
if(low[W] >= Num[V])
printf(“%v Articulation point is”, V);
Low[V] = min(Low[V], Low[W]); /* Rule 3 */
}
else
{
if(parent[V]! = W) /* Back edge */
Low[V] = min(Low[V], Num[W]); /* Rule 2
*/
www.padeepz.n
www.padeepz.n
et
}
}
}
APPLICATION
BICONNECTIVITY ADVANTAGES
DISADVANTAGES
EULER CIRCUIT
EULERIAN PATH
EULERIAN CIRCUIT
www.padeepz.n
www.padeepz.n
et
Unicursal. While such graphs are Eulerian graphs, not every Eulerian graph
possesses an Eulerian cycle.
EULER'S THEOREM
Euler's theorem 1
If a graph has any vertex of odd degree then it cannot have an Euler
circuit.
If a graph is connected and every vertex is of even degree, then it at least
has one Euler circuit.
Euler's theorem 2
If a graph has more than two vertices of odd degree then it cannot
have an Euler path.
If a graph is connected and has just two vertices of odd degree, then it at
least has one Euler path. Any such path must start at one of the odd-
vertices and end at the other odd vertex.
ALGORITHM
1. Check to make sure that the graph is connected and all vertices are
of even degree
2. Start at any vertex
3. Travel through an edge:
o If it is not a bridge for the untraveled part, or
o there is no other alternative
4. Label the edges in the order in which you travel them.
5. When you cannot travel any more, stop.
www.padeepz.n
www.padeepz.n
et
Fleury's Algorithm
Note:
APPLICATION
www.padeepz.n
www.padeepz.n
IMPORTANT SUMS et
1. Topological Sort
V2 V3 VerticesIndegree
V1 0
V2 1 0
V3 1 0 0
V1 V4 V5 V6 V10 V4 1 0
V5 1 0
V6 2 1 0
V7 V8 V9 V7 2 1
0
V8 1 0
V9 1 0
V10 1 0
Enqueue 1 2 4 3 5 V10 V6
V V V V V
V9 V8 V7
Sorted Vertices : Dequeue V1 V2 V4 V3 V5 V10 V6
V9 V8 V7
V1 V2 V4 V3 V5 V10 V6 V9 V8 V7
www.padeepz.n
www.padeepz.n
et
b c
2
a d
6
6 4
f e
void Topsort(Graph G)
Queue Q;
Make Empty(Q);
if (Indegree[V]==0)
enqueue(V,Q);
while(!Isempty(Q))
V = Dequeue(Q);
Topnum[V]=++Counter;
www.padeepz.n
www.padeepz.n
et
if(--Indegree[w]==0)
Enqueue(w,0);
if(counter!=Num Vertex)
Dispose Queue(Q);
void unweighted(Table T)
Queue Q;
Vertex v,w;
IsEmpty(Q))
V = Dequeue(o);
T[V].Known = True;
if(!T[w].Known)
www.padeepz.n
Graphs
gate www.padeepz.n
questi
ons
et
1. (a) How many binary relations are there on a set A with n elements?
(b) How many one-to-one functions are there from a set A with n elements onto itself?
(c) Show that the number of odd degree vertex in a finite graph is even.
(d) Specify an adjacency-lists representation of the undirected graph.
3. Write the adjacency matrix representation of the graph given in fig below:
P1
P5 P2
P4 P3
4. In the graph shown below, the depth-first spanning tree edges are marked with ‘T’. Identify the forward, backward and cross edges.
5. The maximum number of possible edges in an undirected graph with n vertices and k components is .
6. Show that all vertices in an undirected finite graph cannot have distinct degrees, if the graph has at least two vertices
8. Consider a simple connected graph G with n vertices and n edges (n>2). Then which of the following statements are true
www.padeepz.n 5
www.padeepz.n
et
Which one of the following is NOT the sequence of edges added to the minimum spanning tree using Kruskal’s algorithm?
10. Which one of the following is TRUE for any simple connected undirected graph with more that 2 vertices?
11. Consider the following sequences of nodes for the undirected graph given below.
I. abefdgc
II. abefcgd
III. adgebcf
IV. adbcgef
A Depth First Search (DFS) is started at node a. The nodes are listed in the order they are first visited. Which all of the above is (are) possible
output(s)?
12. For the undirected, weighted graph given below, which of the following sequences of edges represents a correct execution of Prim’s algorithm to
construct a Minimum Spanning Tree?
(D) (a, b), (d, f), (f, c), (g, i), (d, a), (g, h), (c, e), (f, h)
(E) (c, e), (c, f), (f, d), (d, a), (a, b), (g, h), (h, f), (g, i)
(F) (d, f), (f, c), (d, a), (a, b), (c, e), (f, h), (g, h), (g, i)
(G) (h, g), (g, i), (h, f), (f, c), (f, d), (d, a), (a, b), (c, e)
www.padeepz.n 6
www.padeepz.n
13.
of G . The resultant graph is sure to be
et
G is a simple undirected graph. Some vertices of G are of odd degree. Add a node v to G and make it adjacent to each odd degree vertex
(A) regular
(B) complete
(C) Hamiltonian
(D) Euler
(A) 2
(B) 3
(C) 4
(D) 5
15.
b -3 e
2 2
1 1 1
a c -5 h f
3 3
2 2
d 2
g
Dijkstra’s single source shortest path algorithm when run from vertex a in the above graph, computes the correct shortest path distance to
16. G is a graph on n vertices and 2n 2 edges. The edges of G can be partitioned into two edge‐disjoint spanning trees. Which of the following is
NOT true for G?
(A) For every subset of k vertices, the induced subgraph has at most 2k 2 edges
(B) The minimum cut in G has at least two edges
(C) There are two edge‐disjoint paths between every pair of vertices
(D) There are two vertex‐disjoint paths between every pair of vertices
17. Which of the following statements is true for every planar graph on n vertices?
18. The Breadth First Search algorithm has been implemented using the queue data structure. One possible order of visiting the nodes of the
following graph is
M N O
R Q P
(A) MNOPQR
(B) NQMPOR
(C) QMNPRO
(D) QMNPOR
www.padeepz.n 7
www.padeepz.n
19.
et
The most efficient algorithm for finding the number of connected components in an undirected graph on n vertices and m edges has time
complexity
(A) (n)
(B) (m)
(C) (m + n)
(D) (mn)
20. What is the largest m such that every simple connected graph with n vertices and n edges contains at least m different spanning trees?
(A) 1 2 3 4 5 6 (B) 1 3 2 4 5 6
(C) 1 3 2 4 6 5 (D) 3 2 4 1 6 5
22. Let G be the non‐planar graph with the minimum possible number of edges. Then G has
23. Consider the depth first search of an undirected graph with 3 vertices P, Q and R. Let discovery time d(u) represent the time instant when the
vertex u is first visited, and finis time f(u) represent the time instant when the vertex u is last visited. Given that
24. Which of the following is the correct decomposition of the directed graph given below into its strongly connected components?
(A) {P, Q, R, S}, {T}, {U}, {V} (B) {P, Q, R, S, T, V}, {U}
www.padeepz.n 8
www.padeepz.n
25.
et
Consider the undirected graph G defined as follows. The vertices of G are bit strings of length n. we have an edge between vertex u and vertex v if
and only if u and v differ in exactly one bit position (in other words, v can be obtained from u by flipping a single bit). The ratio of the chromatic
number of G to the diameter of G is
26. If all the edge weights of an undirected graph are positive, then any subset of edges that connects all the vertices and has minimum total weight is
a
27. In a binary tree, the number of internal nodes of degree 1 is 5, and the number of internal nodes of degree 2 is 10. The number of leaf nodes in the
binary tree is
28. The 2n vertices of a graph G corresponds to all subsets of size n, for n ≥ 6. Two vertices of G are adjacent if and only if the corresponding sets
intersect in exactly two elements.
2n
(A) 2 (B) n +2 (C) 2n/2 (D)
n
The maximum degree of a vertex in G is
29. Let T be a depth first search tree in an undirected graph G. Vertices u and v are leaves of this tree T. The degrees of both u and v in G are at least 2.
Which one of the following statements is true?
Which one of the following cannot be the sequence of edges added, in that order, to a minimum spanning tree using Kruskal’s algorithm?
(A) (a-b), (d-f), (b-f), (d-c), (d-e) (B) (a-b), (d-f), (d-c), (b-f), (d-e)
www.padeepz.n 9
www.padeepz.n
(C) (d-f), (a-b), (d-c), (b-f), (d-e) (D) (d-f), (a-b), (b-f), (d-e), (d-c)
et
31. To implement Dijkstra’s shortest path algorithm on undirected graphs so that it runs in linear time, the data structure to be used is
32. Consider weighted complete graph G on the vertex set {v1, v2, …, vn} such that the weight of the edge (vi, vj) is 2 i j . The weight of a minimum
spanning tree of G is
n
(A) n – 1 (B) 2n – 2 (C) (D) n2
2
33. Let G be a directed graph whose vertex set is the set of number from 1 to 100. There is an edge from a vertex i to a vertex j iff either j = i + 1 or j =
3i. the minimum number of edges in a path in G from vertex 1 to 100 is
34. Let G be a weighted undirected graph and e be an edge with maximum weight in G. Suppose there is minimum weight spanning tree in G
containing edge e. which of the following statements is always true?
35. In the following table, the left column contains the names of standard graph algorithms and the ight column contains the time complexities of the
algorithms. Match each algorithm with its time complexity.
(A) 1→ C, 2→ A, 3→ B, 4→ D
(B) 1→ B, 2→ D, 3→ C, 4→ A
(C) 1→ C, 2→ D, 3→ A, 4→ B
(D) 1→ B, 2→ A, 3→ C, 4→ D
36. In depth first traversal of a graph G with n vertices, k edges are marked as tree edges. The number of connected components in G is
Let s and t be two vertices in a undirected graph G = (V, E) having distinct positive edge weights. Let [X, Y] be partition of V such that s Є X and t Є
Y. Consider the edge e having the minimum weight amongst all those edges that have one vertex in X and one vertex in Y.
www.padeepz.n 10
www.padeepz.n
et
(b) Let the weight of an edge e denote the congestion on that edge. the congestion on a path is defined to be the maximum of the
congestions on the edges of the path. We wish to find the path from s to t having minimum congestion. Which of the following paths is
always such a path of minimum congestion?
38. Postorder traversal of a given binary search tree, T produces the following sequence of keys
10, 9, 23, 22, 27, 25, 15, 50, 95, 60, 40, 29
Which one of the following sequences of keys can be the result of an inorder traversal of tree T?
(A) 9, 10, 15, 22, 23, 25, 27, 29, 40, 50, 60, 95
(B) 9, 10, 15, 22, 40, 50, 60, 95, 23, 25, 27, 29
(C) 29, 15, 9, 10, 25, 22, 23, 27, 40, 60, 50, 95
(D) 95, 50, 60, 40, 27, 23, 22, 25, 10, 9, 15, 29
39. Let G be a simple connected graph with 13 vertices and 19 edges. Then, the number of faces in the planar embedding of the graph is:
(A) 6
(B) 8
(C) 9
(D) 13
40. An undirected graph G has n nodes. its adjacency matrix is given by an n × n square matrix whose (i) diagonal elements are 0’s and
(ii) non‐ diagonal elements are 1’s. Which one of the following is TRUE?
Using Prim’s algorithm to construct a minimum spanning tree starting with node A, which one of the following sequences of edges represents a
possible order in which the edges would be added to construct the minimum spanning tree?
(A) (E, G), (C, F), (F, G), (A, D), (A, B), (A, C)
(B) (A, D), (A, B), (A, C), (C, F), (G, E), (F, G)
(C) (A, B), (A, D), (D, F), (F, G), (G, E), (F, C)
(D) (A, D), (A, B), (D, F), (F, C), (F, G), (G, E)
42. What is the number of vertices in an undirected connected graph with 27 edges, 6 vertices of degree 2, 3 vertices of degree 4 and remaining of
degree 3?
(A) 10
(B) 11
(C) 18
(D) 19
43. What is the number of edges in an acyclic undirected graph with n vertices?
(A) n – 1
www.padeepz.n 11
www.padeepz.n
(B) n
(C) n + 1
(D) 2n – 2
et
44. Let G1 = (V, E1) and G2 = (V, E2) be connected graphs on the same vertex set V with more than two vertices. If G1 G2 = (V, E1 E2) is not a
connected graph, then the graph G1 U G2 = (V, E1 U E2)
45. How many graphs on n labeled vertices exist which have at least (n2 – 3n)/2) edges?
(n ^ 2n) / 2
(A) (n^ 23n) / 2
(n ^ 23n) / 2
(B) Ck
(n ^ 2n)
k 0
(D) C
(n^ 2n) / 2 k
k 0
46. The minimum number of colours required to colour the following graph, such that no two adjacent vertices are assigned the same colour, is
(A) 2
(B) 3
(C) 4
(D) 5
47. Suppose we run Dijkstra’s single source shortest path algorithm on the following edge‐weighted directed graph with vertex P as the source.
In what order do the nodes get included into the set of vertices for which the shortest path distances are finalized?
(A) P, Q, R, S, T, U
(B) P, Q, R, U, S, T
(C) P, Q, R, U, T, S
(D) P, Q, T, R, U, S
48. A binary tree with n 1 nodes has n1 , n2 and n3 nodes of degree one, two and three respectively. The degree of a node is defined as the
number of its neighbours.
(A) n1 n2 1
(B) n1 2
n1 n2
(C)
2
(D) n2 1
Starting with the above tree, while there remains a node v of degree two in the tree, add an edge between the two neighbours of v and then
www.padeepz.n 12
www.padeepz.n
remove v from the tree. How many edges will remain at the end of the process?
et
(A) 2*n1 3
(B) n2 2 * n1 2
(C) n3 n2
(D) n2 n1 2
49. Suppose the BST has been unsuccessfully searched for key 273. Which all of the above sequences list nodes in the order in which we could have
encountered them in the search?
(A) 4
(B) 5
(C) 6
(D) 9
50. In an unweighted, undirected connect graph, the shortest path from a node S to every node is computed most efficiently, in terms of time
complexity, by
begin
then
begin
Visit (v);
end
else
www.padeepz.n 13
www.padeepz.n
begin
end;
et
while LIST is not empty
do
begin
Let v ε LIST;
Visit (v);
end
end
NOTE: Initially Adj (u) is the list of all edges incident to u and LIST is the set of all vertices in the graph. They are globally accessible.
What kinds of sub graphs are obtained when this algorithm traverses the graphs G1 and G2 shown in Fig. 6 and Fig. 7, respectively?
Fig. 6 Fig. 7
(a) What is the commonly known traversal of graphs that can be obtained from the sub graphs generated by Program Explore?
(b) Show that the time complexity of the procedure is O (v + e) for a graph with v vertices and e edges, given that each vertex can be accessed
and removed from LIST in const time. Also show that all edges of the graph are traversed.
52. The maximum number of possible edges in an undirected graph with n vertices and k components is .
53. Kruskal’s algorithm for finding a minimum spanning tree of a weighted graph G with n vertices and m edges has the time‐complexity of:
A. (n2)
B. (m n)
C. (m + n)
D. (m log n)
E. (m2)
54. Show that all vertices in an undirected finite graph cannot have distinct degrees, if the graph has at least two vertices
55. Complexity of Kruskal’s algorithm for finding the minimum spanning tree of an undirected graph containing n vertices and m edges, if the edges
are sorted is .
58. How many edges are there in a forest with p components having n vertices in all?
59. An independent set in a graph is a subset of vertices such that no two vertices in the subset are connected by an edge. An incomplete scheme for
greedy algorithm to find a maximum independent set in a tree is given below:
I: = φ do
www.padeepz.n 14
www.padeepz.n
begin
V: = V –{u};
If u is such that
then I: = I U{u}
end;
Output (I);
Complete the algorithm by specifying the property of vertex u in each case. (4)
60. Consider a simple connected graph G with n vertices and n edges (n>2). Then which of the following statements are true
61. The number of distinct simple graphs with upto three nodes is
(A) 15
(B) 10
(C) 7
(D) 9
62. The number of edges in a regular graph of degree d and n vertices are …………….
(A) n ‐ 1
(B) n
(C) n + 1
(D) None of the above
64. How many minimum spanning trees does the following graph have? Draw them (weights are assigned to the edges).
65. Prove that in finite graph, the number of vertices of odd degree is always even.
66. A complete undirected, weighted graph G is given on the vertex set {0, 1, ..,n‐1} for any fixed ‘n’. Draw the minimum spanning tree of G if
www.padeepz.n 15
www.padeepz.n
et
Fig. 17
(a) Output the sequence of vertices identified by the Dijkstra’s algorithm for single source shortest path when the algorithm is started at
node A. (2)
(b) Write down the sequence of vertices in the shortest path from A to E. (2)
(c) What is the cost of shortest path from A to E?
68. Which of the following algorithm design techniques is used in finding all pairs of shortest distances in a graph?
69. Consider a graph whose vertices are points in the plane with integer co‐ordinates (x,y) such that 1 ≤ x ≤ n and 1 ≤ y ≤ n, where n ≥ 2 is an integer.
Two vertices (x1, y1) and (x2, y2) are adjacent iff |x1 – x2| ≤ 1v |y1 – y2| ≤ 1. The weight of na edge {(x1, y1), (x2, y2)} is
What is the weight of a maximum weight spanning tree in this graph? Write only the answer without any explanations.
70. Let G be a graph with 100 vertices numbered 1 to 100. Two vertices i and j are adjacent iff |i – j| = 8 or |i – j| = 12. The number of connected
components in G is
(A) 0
(B) 1
(C) 2
(D) 3
72. Let G be an undirected graph with distinct edge weights. Let emax be the edge with maximum weight and emin the edge with minimum weight.
www.padeepz.n 16
www.padeepz.n
et
(D)
G has a unique minimum spanning tree
73. Let G be an undirected graph. Consider a depth first traversal G, and let T be the resulting depth first search tree. Let u be a vertex in G and v be
the first new (unvisited) vertex visited after visiting u in the traversal. Which of the following is always true?
74. How many undirected graphs (not necessarily connected) can be constructed out of a given set And = {v 1, v2, …, vn} of n vertices?
A. n(n‐1)/2
B. 2n
C. n!
D. 2n(n – 1)/2
75. Consider a weighted undirected graph with vertex set And = {n1, n2, n3, n4, n5, n6} and edge set E = {(n1, n2, 2), (n1, n3, 8), (n1, n6, 3), (n2, n4, 4), (n2,
n5, 12), (n3, n4, 7), (n4, n5, 9), (n4, n6, 4)} The third value in each tuple represents the weight of the edge specified in the tuple.
(a) Lists the edges of a minimum spanning tree of the graph. (2)
(b) How many distinct minimum spanning tree does this graph have?
(c) Is the minimum among the edge weights of a minimum spanning tree unique over all possible minimum spanning trees of a graph? (1)
(d) Is the maximum among the edge weights of a minimum spanning tree unique over all possible minimum spanning trees of a graph?
76. The minimum number of colors required to color the vertices of a cycle with n nodes in such a way that no two adjacent nodes have the same
color is:
A. 2
B. 3
C. 4
D. n – 2 n/2 + 2
77. The Maximum number of edges in a n –node undirected graph without self loops is
A. n2
B. n(n – 1)/2
C. n ‐1
D. (n+1)(n)/2
78. The number of distinct simple graphs with upto three nodes is
(E) 15
(F) 10
(G) 7
(H) 9
79. Fill in the blanks in the following template of an algorithm to compute all pairs shortest path lengths in a directed graph G with n*n adjacency
matrix A. A[i, j] equals 1 if there is an edge in G from i to j, and 0 otherwise. Your aim in filling in the blanks
INITIALIZATION: For I = 1 … n
{For j = 1 … n
{ For j = 1 … n
www.padeepz.n 17
www.padeepz.n
{ For k = 1 … n
(a) Copy the complete line containing the blanks in the Initialization step and fill in the blanks. (1)
(b) Copy the complete line containing the blanks in the Initialization step and fill in the blanks. (3)
(c) Fill in the blank: The running time of the algorithm is O( )
80. Let G be an arbitrary graph with n nodes and k components. If a vertex is removed from G, the number of components in the resultant graph
must necessarily lie between
(A) k and n
(B) k – 1 and k + 1
(C) k – 1 and n – 1
(D) k + 1 and n – k
I abeghf
II abfehg
III abfhge
IV afghbe
82. How many perfect matching are there in a complete graph of 6 vertices?
(A) 15
(B) 24
(C) 24
(D) 60
83. Let G = (V, E) be an undirected graph with a subgraph G1 = (V1, E1). Weights are assigned to edges of G as follows.
A single‐source shortest path algorithm is executed on the weighted graph (V, E, what) with an arbitrary vertex v1 of V1 as the source.
Which of the following can always be inferred from the path costs computed?
(A) The number of edges in the shortest paths from v1 to all vertices of G
(B) G1 is connected.
(C) V1 forms a clique in G
(D) G1 is a tree
www.padeepz.n 18
www.padeepz.n
84. What is the weight of a minimum spanning tree of the following graph?
et
(A) 29
(B) 31
(C) 38
(D) 41
www.padeepz.n 19
www.padeepz.n
et
for each w adjacent to v
if(!T[w].Known)
/* update of w */
T[w].path = v;
Dispose Queue(Q);
www.padeepz.n
www.padeepz.n
UNIT V SORTING, SEARCHING AND HASH TECHNIQUES
et
Sorting algorithms: Insertion sort - Selection sort - Shell sort - Bubble sort - Quick sort - Merge
sort - Radix sort – Searching: Linear search –Binary Search Hashing: Hash Functions – Separate
Chaining – Open Addressing – Rehashing – Extendible Hashing.
SORTING:
Definition:
Sorting is a technique for arranging data in a particular order.
Order of sorting:
Order means the arrangement of data. The sorting order can be ascending or descending. The
ascending order means arranging the data in increasing order and descending order means
arranging the data in decreasing order.
Types of Sorting
Internal Sorting
External Sorting
Internal Sorting
Internal Sorting is a type of sorting technique in which data resides on main memory of
computer. It is applicable when the number of elements in the list is small.
E.g. Bubble Sort, Insertion Sort, Shell Sort, Quick Sort., Selection sort, Radix sort
External Sorting
External Sorting is a type of sorting technique in which there is a huge amount of data and it resides on
secondary devise(for eg hard disk,Magnetic tape and so no) while sorting.
E.g. Merge Sort, Multiway Merge Sort,Polyphase merge sort
Sorting can be classified based on
1.Computational complexity
2.Memory utilization
3. Stability
4. Number of comparisons.
ANALYSIS OF ALGORITHMS:
Efficiency of an algorithm can be measured in terms of:
www.padeepz.n
www.padeepz.n
Sorting algorithms:
et
Insertion sort
Selection sort
Shell sort
Bubble sort
Quick sort
Merge sort
Radix sort
INSERTION SORTING:
The insertion sort works by taking elements from the list one by one and inserting them
in the correct position into a new sorted list.
Insertion sort consists of N-1 passes, where N is the number of elements to be sorted.
The ith pass will insert the ith element A[i] into its rightful place among A[1],A[2],
…,A[i-1].
After doing this insertion the elements occupying A[1],…A[i] are in sorted order.
www.padeepz.n
www.padeepz.n
for ( j = i ; j > 0 && a [ j -1 ] > temp ; j -- )
et
{
a[ j ] = a [ j – 1 ] ;
}
a[j]=temp;
}}
Program for Insertion sort
#include<stdio.h>
void main( ){
int n, a[ 25 ], i, j, temp;
printf( "Enter number of elements \n" );
scanf( "%d", &n );
printf( "Enter %d integers \n", n );
for ( i = 0; i < n; i++ )
scanf( "%d", &a[i] );
for ( i = 0 ; i < n; i++ ){
temp=a[i];
for (j=i;j > 0 && a[ j -1]>temp;j--)
{
a[ j ] = a[ j - 1 ];
}
a[j]=temp;}
printf( "Sorted list in ascending order: \n ");
for ( i = 0 ; i < n ; i++)
printf ( "%d \n ", a[ i ] );}
OUTPUT:
Enter number of elements
6
Enter 6 integers
20 10 60 40 30 15
Sorted list in ascending order:
10
15
20
30
40
60
Advantage of Insertion sort
Simple implementation.
Efficient for (quite) small data sets.
Efficient for data sets that are already substantially sorted.
www.padeepz.n
www.padeepz.n
Disadvantages of Insertion sort
et
It is less efficient on list containing more number of elements.
As the number of elements increases the performance of the program would be slow.
Insertion sort needs a large number of element shifts.
Selection Sort
Selection sort selects the smallest element in the list and place it in the first position then selects
the second smallest element and place it in the second position and it proceeds in the similar way
until the entire list is sorted. For “n” elements, (n-1) passes are required. At the end of the i th
iteration, the ith smallest element will be placed in its correct position.
www.padeepz.n
www.padeepz.n
Program for Selection sort
et
#include <stdio.h>
void main( )
{
int a [ 100 ] , n , i , j , position , temp ;
printf ( "Enter number of elements \n" ) ;
scanf ( "%d", &n ) ;
printf ( " Enter %d integers \n ", n ) ;
for ( i = 0 ; i < n ; i ++ )
scanf ( "%d", & a[ i ] ) ;
for ( i = 0 ; i < ( n - 1 ) ; i ++ )
{
position = i ;
for ( j = i + 1 ; j < n ; j ++ )
{
if ( a [ position ] > a [ j ] )
position = j ;
}
if ( position != i )
{
temp = a [ i ] ;
a [ i ] = a [ position ] ;
a [ position ] = temp ;
}
}
printf ( "Sorted list in ascending order: \n ") ;
for ( i = 0 ; i < n ; i ++ )
printf ( " %d \n ", a[ i ] ) ;
}
OUTPUT:
Enter number of elements
5
Enter 5 integers
83951
Sorted list in ascending order:
1
3
5
8
9
Advantages of selection sort
• Memory required is small.
• Selection sort is useful when you have limited memory available.
• Relatively efficient for small arrays.
www.padeepz.n
www.padeepz.n
Disadvantage of selection sort
et
• Poor efficiency when dealing with a huge list of items.
• The selection sort requires n-squared number of steps for sorting n elements.
• The selection sort is only suitable for a list of few elements that are in random order.
Shell Sort
• Invented by Donald shell.
• It improves upon bubble sort and insertion sort by moving out of order elements more
than one position at a time.
• In shell sort the whole array is first fragmented into K segments, where K is preferably a
prime number.
• After the first pass the whole array is partially sorted.
• In the next pass, the value of K is reduced which increases the size of each segment and
reduces the number of segments.
• The next value of K is chosen so that it is relatively prime to its previous value.
• The process is repeated until K=1 at which the array is sorted.
• The insertion sort is applied to each segment so each successive segment is partially
sorted.
• The shell sort is also called the Diminishing Increment sort, because the value of k
decreases continuously
www.padeepz.n
www.padeepz.n
et
www.padeepz.n
www.padeepz.n
for ( i = k ; i < n ; i ++ )
et
{
temp = a [ i ] ;
for (j = i ; j>= k && a [ j - k ]>temp ; j=j - k )
{
a[j]=a[j-k];
}
a [ j ] = temp ;
}
}
printf( "Sorted list in ascending order using shell sort: \n ");
for ( i = 0 ; i < n ; i++)
printf ( "%d\t ", a[ i ] );
}
OUTPUT:
Enter number of elements
10
Enter 10 integers
81 94 11 96 12 35 17 95 28 58
Sorted list in ascending order using shell sort:
11 12 17 28 35 58 81 94 95 96
//PROGRAM FOR SHELL USING FUNCTION
#include < stdio.h >
void main( )
{
int a [ 5 ] = { 4, 5, 2, 3, 6 } , i = 0 ;
ShellSort ( a, 5 ) ;
printf(“Example using function”);
printf( " After Sorting :" ) ;
for ( i = 0 ; i < 5 ; i ++ )
printf ( " %d ", a[ i ] ) ;
}
void ShellSort (int a [ 5 ] , int n )
{
int i , j , k , temp ;
for ( k = n / 2 ; k > 0 ; k / = 2)
{
for ( i = k ; i < n ; i ++ )
{
temp = a [ i ] ;
for ( j = i ; j > = k && a [ j – k ] > temp ; j = j – k ){
a[j]=a[j–k];
}
a [ j ] = temp ; } }}
www.padeepz.n
www.padeepz.n
OUTPUT:
et
After Sorting : 2 3 4 5 6
Advantages of Shell sort
• Efficient for medium-size lists.
Disadvantages of Shell sort
• Complex algorithm, not nearly as efficient as the merge, heap and quick sorts
Bubble Sort
Bubble sort is one of the simplest internal sorting algorithms.
Bubble sort works by comparing two consecutive elements and the largest element
among these two bubbles towards right at the end of the first pass the largest element gets
sorted and placed at the end of the sorted list.
This process is repeated for all pairs of elements until it moves the largest element to the
end of the list in that iteration.
Bubble sort consists of (n-1) passes, where n is the number of elements to be sorted.
In 1st pass the largest element will be placed in the nth position.
In 2nd pass the second largest element will be placed in the (n-1)th position.
In (n-1)th pass only the first two elements are compared.
www.padeepz.n
www.padeepz.n
for( j = 0; j < n – i - 1; j++ ) et
{
if( a[ j ] > a [ j + 1 ] )
{
temp = a [ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = temp;
}
} }}
www.padeepz.n
www.padeepz.n
Disadvantage of Bubble sort
et
• The major drawback is the amount of time it takes to sort.
• The average time increases almost exponentially as the number of table elements
increase.
Quick Sort
Quicksort is a divide and conquer algorithm.
The basic idea is to find a “pivot” item in the array and compare all other items with pivot
element.
Shift items such that all of the items before the pivot are less than the pivot value and all
the items after the pivot are greater than the pivot value.
After that, recursively perform the same operation on the items before and after the pivot.
Find a “pivot” item in the array. This item is the basis for comparison for a single round.
Start a pointer (the left pointer) at the first item in the array.
Start a pointer (the right pointer) at the last item in the array.
1.
Assume A[0]=pivot which is the left. i.e pivot=left.
2.
Set i=left+1; i.e A[1];
3.
Set j=right. ie. A[6] if there are 7 elements in the array
4.
If A[pivot]>A[i],increment i and if A[j]>A[pivot],then decrement j, Otherwise swap A[i]
and A[j] element.
5. If i=j,then swap A[pivot] and A[j].
www.padeepz.n
www.padeepz.n
et
www.padeepz.n
www.padeepz.n
Quick Sort routine: et
void Quicksort ( int a [ ], int left, int right )
{
int i, j, p, temp;
if ( left < right )
{
p = left;
i = left + 1; j
= right;
while ( i < j )
{
while ( a [ i ] < = a [ p ] )
i = i + 1;
while ( a [ j ] > a [ p ] )
j = j - 1;
if ( i < j )
{
temp = a [ i ];
a [ i ] = a [ j ];
a [ j ] = temp;
}
}
temp = a [ p ];
a [ p ] = a [ j ];
a [ j ] = temp;
quicksort ( a, left, j - 1 );
quicksort ( a, j + 1, right
);
}}
Program for Quick sort
#include<stdio.h>
void quicksort (int [10], int, int ) ;
void main( )
{
int a[20], n, i ;
printf("Enter size of the array:" );
scanf("%d",&n);
printf( " Enter the numbers :");
for ( i = 0 ; i < n ; i ++ )
scanf ("%d",&a[i]);
quicksort ( a , 0 , n - 1 );
printf ( " Sorted elements: " );
for ( i = 0 ; i < n ; i ++ )
printf ("%d\t",a[ i]);
}
www.padeepz.n
www.padeepz.n
void quicksort ( int a[10], int left, int right )
{ et
int p, j, temp, i ;
if ( left < right )
{
p = left ;
i = left ;
j = right ;
while ( i < j )
{
while(a[i]<= a[p] && i<right )
i++ ;
while ( a [ j ] > a [ p ] )
j--;
if ( i < j )
{
temp = a [ i ] ;
a[i]=a[j];
a[ j ] = temp ;
}
}
temp = a [ p ] ;
a[p]=a[j];
a [ j ] =temp ;
quicksort ( a , left , j - 1 ) ;
quicksort ( a , j + 1 , right ) ;
}
}
OUTPUT:
Enter size of the array:8
www.padeepz.n
www.padeepz.n
Merge Sort
et
Merge sort is a sorting algorithm that uses the divide, conquer, and combine algorithmic
paradigm.
Divide means partitioning the n-element array to be sorted into two sub-arrays of n/2 elements.
If there are more elements in the array, divide A into two sub-arrays, A1 and A2, each containing
about half of the elements of A.
Conquer means sorting the two sub-arrays recursively using merge sort.
Combine means merging the two sorted sub-arrays of size n/2 to produce the sorted array of n
elements.
The basic steps of a merge sort algorithm are as follows:
If the array is of length 0 or 1, then it is already sorted.
Otherwise, divide the unsorted array into two sub-arrays of about half the size.
Use merge sort algorithm recursively to sort each sub-array.
Merge the two sub-arrays to form a single sorted list.
www.padeepz.n
void msort ( int a[ ] , int temp [ ] , int left , int right ) www.padeepz.n
{ int center ;
if( left < right ){ et
center = ( left + right ) / 2 ;
msort ( a , left , center ) ;
msort ( a , temp , center + 1 , right ) ;
merge ( a , temp , n , left , center , right )
;
}}
void merge ( int a [ ] , int temp [ ] , int n , int left , int center , int right )
{
int i = 0 , j , left_end = center , center = center + 1 ;
while( ( left < = left_end ) && ( center < = right ) )
{
if( a [ left ] < = a [ center ] )
{
temp [ i ] = a [ left ] ;
i++;
left + + ;
}
else
{
temp [ i ] = a [ center ] ;
i++;
center + + ;
}
}
while( left <= left_end )
{
temp [ I ] = a [ left ] ;
left + + ;
i++;
}
while( center < = right )
{
temp [ i ] = a [ center ] ;
center + + ;
i++;
}
for ( i = 0 ; i < n ; i + + )
print temp [ i ] ;
}
www.padeepz.n
www.padeepz.n
et
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1); printf("\
nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion mergesort(a,mid+1,j);
//right recursion merge(a,i,mid,mid+1,j); //merging of two
sorted sub-arrays
}}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{ if(a[i]<a[j])
temp[k++]=a[i++];
else temp[k+
+]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second
list temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
www.padeepz.n
www.padeepz.n
OUTPUT:
et
Enter no of elements:8
Enter array elements:24 13 26 1 2 27 38 15
Sorted array is :1 2 13 15 24 26 27 38
Advantages of Merge sort
• Mergesort is well-suited for sorting really huge amounts of data that does not fit into
memory.
• It is fast and stable algorithm
Radix Sort
Radix sort is one of the linear sorting algorithms. It is generalized form of bucket sort. It
can be performed using buckets from 0 to 9.
It is also called binsort, card sort.
It works by sorting the input based on each digit. In first pass all the elements are stored
according to the least significant digit.
In second pass the elements are arranged according to the next least significant digit and
so on till the most significant digit.
The number of passes in a Radix sort depends upon the number of digits in the given
numbers.
Step2: Consider the LSB (Least Significant Bit) of each number (numbers in the one‟s
Step3: Place the elements in their respective buckets according to the LSB of each number
Step5: repeat the same process with the digits in the 10‟s place (e.g. In 43 MSB =4)
Step6: repeat the same step till all the digits of the given number are consider.
www.padeepz.n
www.padeepz.n
Consider the following numbers to be sorted using Radix sort.
et
www.padeepz.n
www.padeepz.n
large = large / 10 ;
et
}
for ( passes = 0 ; passes < num ; passes ++ )
{
for ( k = 0 ; k < 10 ; k ++ )
{
buck [ k ] = 0 ;
}
for ( i = 0 ; i < n ; i ++ )
{
l = ( ( a [ i ] / div ) % 10 ) ;
bucket [ l ] [ buck [ l ] ++ ] = a [ i ] ;
}
i=0
;
for ( k = 0 ; k < 10 ; k ++ )
{
for ( j = 0 ; j < buck [ k ] ; j ++ )
{
a [ i ++ ] = bucket [ k ] [ j ] ;
}
}
div * = 10 ;
}
}
}
#include<stdio.h >
void main( )
{
int a [ 5 ] = { 4, 5, 2, 3, 6 } , i = 0 ;
void Radix_sort ( int a [ ] , int n );
Radix_sort(a,5);
printf( " After Sorting :" ) ;
for ( i = 0 ; i < 5 ; i ++ )
printf ( " %d ", a[ i ] ) ;
}
void Radix_sort ( int a [ ] , int n )
{
int bucket [ 10 ] [ 5 ] , buck [ 10 ] , b [ 10 ] ;
int i , j , k , l , num , div , large , passes ;
div = 1 ;
num = 0 ;
large = a [ 0 ] ;
for ( i = 0 ; i < n ; i ++ ){
www.padeepz.n
if ( a[ i] > large )
www.padeepz.n
{ et
large = a [ i ] ;
}
while ( large > 0 )
{
num ++ ;
large = large / 10 ;
}
for ( passes = 0 ; passes < num ; passes ++ )
{
for ( k = 0 ; k < 10 ; k ++ )
{
buck [ k ] = 0 ;
}
for ( i = 0 ; i < n ; i ++ )
{
l = ( ( a [ i ] / div ) % 10 ) ;
bucket [ l ] [ buck [ l ] ++ ] = a [ i ] ;
}
i=0
;
for ( k = 0 ; k < 10 ; k ++ )
{
for(j=0 ; j<buck[k];j++ )
{
a[i++]=bucket[ k ][ j ] ;
}
}
div*= 10 ;
}
}
}
www.padeepz.n
www.padeepz.n
Analysis of Sorting algorithms:
et
S.No Algorithm Best Case Analysis Average Case Worst Case
Analysis Analysis
1 Insertion sort O(N) O(N2) O(N2)
2 Selection sort O(N2) O(N2) O(N2)
3 Shell sort O(N log N) O(N1.5) O(N2)
4 Bubble sort O(N2) O(N2) O(N2)
5 Quick sort O(N log N) O(N log N) O(N 2)
6 Merge sort O(N log N) O(N log N) O(N log N)
7 Radix or bucket or O(N log N) O(N log N) O(N log N)
binsort sort or card
sort
SEARCHING
Searching is an algorithm, to check whether a particular element is present in the list.
Types of searching:-
Linear search
Binary Search
Linear Search
Linear search is used to search a data item in the given set in the sequential manner, starting from
the first element. It is also called as sequential search
www.padeepz.n
www.padeepz.n
Program for Linear search
et
#include < stdio.h >
void main( )
{
int a [ 10 ] , n , i , search, count = 0 ;
printf ( " Enter the number of elements \ t " ) ;
scanf ( " %d " , & n ) ;
printf ( " \n Enter %d numbers \n " , n ) ;
for ( i = 0 ; i < n ; i ++ )
scanf ( " %d " , & a [ i ] ) ;
printf ( " \n Array Elements \n " ) ;
for ( i = 0 ; i < n ; i ++ )
printf ( " %d \t " , a [ i ] ) ;
printf ( " \ n \ n Enter the Element to be searched: \ t " ) ;
scanf ( " % d " , & search ) ;
for ( i =0 ; i < n; i ++ )
{
if ( search = = a [ i ] )
count ++ ;
}
if ( count = = 0 )
printf( " \n Element %d is not present in the array " , search ) ;
else
printf ( " \n Element %d is present %d times in the array \n " , search , count ) ;
}
OUTPUT:
Enter the number of elements 5
Enter the numbers
20 10 5 25 100
Array Elements
20 10 5 25 100
Enter the Element to be searched: 25
Element 25 is present 1 times in the array
www.padeepz.n
www.padeepz.n
Binary Search
et
Binary search is used to search an item in a sorted list. In this method , initialize the lower
limit and upper limit.
The middle position is computed as (first+last)/2 and check the element in the middle
position with the data item to be searched.
If the data item is greater than the middle value then the lower limit is adjusted to one
greater than the middle value.Otherwise the upper limit is adjusted to one less than the
middle value.
Working principle:
Algorithm is quite simple. It can be done either recursively or iteratively:
1. Get the middle element;
2. If the middle element equals to the searched value, the algorithm stops;
3. Otherwise, two cases are possible:
o Search value is less than the middle element. In this case, go to the step 1 for the
part of the array, before middle element.
o Searched value is greater, than the middle element. In this case, go to the step 1
for the part of the array, after middle element.
Example 1.
www.padeepz.n
www.padeepz.n
last = mid – 1 ;
et
mid = ( first + last ) / 2 ;
}
if( first > last )
print “Element Not Found” ;
}
Program for Binary Search:
#include<stdio.h>
void main( )
{
int a [ 10 ] , n , i , search, count = 0 ;
void Binary_search ( int a[ ] , int n , int search );
printf ("Enter the number of elements \t") ;
scanf ("%d",&n); printf("\
nEnter the numbers\n") ; for (i =
0; i<n;i++)
scanf("%d",&a[i]); printf("\
nArray Elements\n") ; for (i =
0 ; i < n ; i ++ ) printf("%d\
t",a[i]) ;
printf ("\n\nEnter the Element to be searched:\t");
scanf("%d",&search );
Binary_search(a,n,search);
}
void Binary_search ( int a[ ] , int n , int search )
{
int first, last, mid ;
first = 0 ;
last = n-1 ;
mid = (first + last ) / 2 ;
while (first<=last )
{
if(search>a[mid])
first = mid + 1 ;
else if (search==a[mid])
{
printf("Element is present in the list");
break ;
}
else
last = mid - 1 ;
mid = ( first + last ) / 2 ;
}
if( first > last )
printf("Element Not Found");
}
www.padeepz.n
www.padeepz.n
OUTPUT:
et
Enter the number of elements 5
Enter the numbers
20 25 50 75 100
Array Elements
20 25 50 75 100
Enter the Element to be searched: 75
Element is present in the listPress any key to continue . . .
Advantages of Binary search:
In Linear search, the search element is compared with all the elements in the array. Whereas
in Binary search, the search element is compared based on the middle element present in the
array.
A technique for searching an ordered list in which we first check the middle item and - based
on that comparison - "discard" half the data. The same procedure is then applied to the
remaining half until a match is found or there are no more items left.
Disadvantages of Binary search:
Binary search algorithm employs recursive approach and this approach requires more
stack space.
It requires the data in the array to be stored in sorted order.
It involves additional complexity in computing the middle element of the array.
Analysis Analysis
1 Linear search O(1) O(N) O(N)
2 Binary search O(1) O(log N) O(log N)
www.padeepz.n
www.padeepz.n
HASHING :
et
Hashing is a technique that is used to store, retrieve and find data in the data structure
called Hash Table. It is used to overcome the drawback of Linear Search (Comparison) &
Binary Search (Sorted order list). It involves two important concepts-
Hash Table
Hash Function
Hash table
A hash table is a data structure that is used to store and retrieve data (keys) very
quickly.
It is an array of some fixed size, containing the keys.
Hash table run from 0 to Tablesize – 1.
Each key is mapped into some number in the range 0 to Tablesize – 1.
This mapping is called Hash function.
Insertion of the data in the hash table is based on the key value obtained from the
hash function.
Using same hash key value, the data can be retrieved from the hash table by few
or more Hash key comparison.
The load factor of a hash table is calculated using the formula:
(Number of data elements in the hash table) / (Size of the hash table)
Hash function
Table size.
Collision handling scheme
0
1
2
3
.
. Simple Hash table with table size = 10
8
9
www.padeepz.n
www.padeepz.n
Hash function:
et
It is a function, which distributes the keys evenly among the cells in the Hash
Table.
Using the same hash function we can retrieve data from the hash table.
Hash function is used to implement hash table.
The integer value returned by the hash function is called hash key.
If the input keys are integer, the commonly used hash function is
www.padeepz.n
www.padeepz.n
et
E.g. consider the following data or record or key (36, 18, 72, 43, 6) table size = 8
93 44
www.padeepz.n
www.padeepz.n
E.g. Key 107
et
H(107)=Floor(50*(107*0.61803398987))
=Floor(3306.481845)
H(107)=3306
Consider table size is 5000
3306 107
4999
The folding method for constructing hash functions begins by dividing the item into
equal-size pieces (the last piece may not be of equal size). These pieces are then added together
to give the resulting hash key value. For example, if our item was the phone number 436-555-
4601, we would take the digits and divide them into groups of 2 (43, 65, 55, 46, 01). After the
addition, 43+65+55+46+01, we get 210. If we assume our hash table has 11 slots, then we need
to perform the extra step of dividing by 11 and keeping the remainder. In this case 210 % 11 is 1,
so the phone number 436-555-4601 hashes to slot 1.
6-555-4601
www.padeepz.n
www.padeepz.n
Collision:
et
If two more keys hashes to the same index, the corresponding records cannot be stored in the
same location. This condition is known as collision.
Characteristics of Good Hashing Function:
www.padeepz.n
www.padeepz.n
Structure Definition for Node
et
typedef Struct node *Position;
Struct node
{
int data; defines the nodes
Position next;
};
www.padeepz.n
www.padeepz.n
P = find ( key, H );
et
if(P = = NULL)
{
newnode = malloc(sizeof(Struct node));
L = H TheLists[Hash(key,Tablesize)];
newnode nex t= L next;
newnode data = key;
L next = newnode;
}}
Position find( int key, Hashtable H){
Position P, List L;
L = H TheLists[Hash(key,Tablesize)];
P = L next;
while(P != NULL && P data != key)
P = P next;
return P;}
If two keys map to same value, the elements are chained together.
Initial configuration of the hash table with separate chaining. Here we use SLL(Singly Linked List)
concept to chain the elements.
NULL
0
NULL
1
NULL
2
NULL
3
NULL
4
NULL
5
NULL
6
NULL
7
NULL
8
NULL
9
www.padeepz.n
www.padeepz.n
et
Insert the following four keys 22 84 35 62 into hash table of size 10 using separate chaining.
The hash function is
H(key) = key % 10
1. H(22) = 22 % 10 =2 2. 84 % 10 = 4
3.H(35)=35%10=5 4. H(62)=62%10=2
www.padeepz.n
www.padeepz.n
Advantages
et
1. More number of elements can be inserted using array of Link List
Disadvantages
1. It requires more pointers, which occupies more memory space.
2.Search takes time. Since it takes time to evaluate Hash Function and also to traverse the
List
Open Addressing
Closed Hashing
Collision resolution technique
Uses Hi(X)=(Hash(X)+F(i))mod Tablesize
When collision occurs, alternative cells are tried until empty cells are
found. Types:-
Linear Probing
Quadratic Probing
Double Hashing
Hash function
H(key) = key % table size.
Insert Operation
To insert a key; Use the hash function to identify the list to which the
element should be inserted.
Then traverse the list to check whether the element is already present.
If exists, increment the count.
Else the new element is placed at the front of the list.
Linear Probing:
Easiest method to handle collision.
Apply the hash function H (key) = key % table size
Hi(X)=(Hash(X)+F(i))mod Tablesize,where F(i)=i.
How to Probing:
first probe – given a key k, hash to H(key)
second probe – if H(key)+f(1) is occupied, try H(key)+f(2)
And so forth.
Probing Properties:
We force f(0)=0
The ith probe is to (H (key) +f (i)) %table size.
If i reach size-1, the probe has failed.
Depending on f (i), the probe may fail sooner.
Long sequences of probe are costly.
Probe Sequence is:
H (key) % table size
H (key)+1 % Table size
H (Key)+2 % Table size
www.padeepz.n
www.padeepz.n
1. H(Key)=Key mod Tablesize
et
This is the common formula that you should apply for any hashing
If collocation occurs use Formula 2
2. H(Key)=(H(key)+i) Tablesize
Where i=1, 2, 3, …… etc
Example: - 89 18 49 58 69; Tablesize=10
1. H(89) =89%10
=9
2. H(18) =18%10
=8
3. H(49) =49%10
=9 ((coloids with 89.So try for next free cell using formula 2))
i=1
h1(49) = (H(49)+1)%10
= (9+1)%10
=10%10
=0
4. H(58) =58%10
=8 ((colloids with 18))
i=1
h1(58) = (H(58) +1)%10
= (8+1) %10
=9%10
=9 =>Again collision
i=2 h2(58) =(H(58)+2)%10
=(8+2)%10
=10%10
=0 =>Again collision
www.padeepz.n
www.padeepz.n
EMPTY 89 18 49 58
et
69
0 49 49 49
1 58 58
2 69
3
4
5
6
7
8 18 18 18
9 89 89 89 89
Linear probing
Quadratic Probing
To resolve the primary clustering problem, quadratic probing can be used. With quadratic
probing, rather than always moving one spot, move i2 spots from the point of collision, where
i is the number of attempts to resolve the collision.
Another collision resolution method which distributes items more evenly.
www.padeepz.n
www.padeepz.n
et
From the original index H, if the slot is filled, try cells H+12, H+22, H+32,.., H + i2 with
wrap-around.
Hi(X)=(Hash(X)+F(i))mod
Tablesize,F(i)=i2 Hi(X)=(Hash(X)+ i2)mod
Tablesize
Limitation: at most half of the table can be used as alternative locations to resolve collisions.
This means that once the table is more than half full, it's difficult to find an empty spot. This
new problem is known as secondary clustering because elements that hash to the same hash
key will always probe the same alternative cells.
Double Hashing
Double hashing uses the idea of applying a second hash function to the key when a
collision occurs. The result of the second hash function will be the number of positions forms
the point of collision to insert.
There are a couple of requirements for the second function:
It must never evaluate to 0 must make sure that all cells can be probed.
Hi(X)=(Hash(X)+i*Hash2(X))mod Tablesize
A popular second hash function is:
Hash2 (key) = R - (key % R) where R is a prime number that is smaller than the size of the
table.
www.padeepz.n
www.padeepz.n
et
Rehashing
Once the hash table gets too full, the running time for operations will start to take too
long and may fail. To solve this problem, a table at least twice the size of the original will be
built and the elements will be transferred to the new table.
Advantage:
A programmer doesn‟t worry about table system.
Simple to implement
Can be used in other data structure as well
The new size of the hash table:
should also be prime
will be used to calculate the new insertion spot (hence the name rehashing)
This is a very expensive operation! O(N) since there are N elements to rehash and the
table size is roughly 2N. This is ok though since it doesn't happen that often.
The question becomes when should the rehashing be applied?
Some possible answers:
once the table becomes half full
once an insertion fails
www.padeepz.n
www.padeepz.n
et
once a specific load factor has been reached, where load factor is the ratio of the
number of elements in the hash table to the table size
Extendible Hashing
Extendible Hashing is a mechanism for altering the size of the hash table to accommodate
new entries when buckets overflow.
Common strategy in internal hashing is to double the hash table and rehash each entry.
However, this technique is slow, because writing all pages to disk is too expensive.
Therefore, instead of doubling the whole hash table, we use a directory of pointers to
buckets, and double the number of buckets by doubling the directory, splitting just the
bucket that overflows.
Since the directory is much smaller than the file, doubling it is much cheaper. Only one
page of keys and pointers is split.
000 100 0 1
010 100
100 000
111 000 000 100 100 000
001 000 010 100 111 000
011 000 001 000 101 000
101 000 011 000 111 001
111 001
001 010
101 100
101 110
www.padeepz.n
www.padeepz.n
00 01 10 11
et
www.padeepz.n
www.padeepz.n
SET-2
et
Arrays, Tables and Set
1. A hash table with ten buckets with one slot per bucket is shown in Figure 1, with the symbols S1 to S7 entered into it using some hashing function
with linear probing. The worst case number of comparison required when the symbol being searched is not in the table is ……………………….
0 S7
1 S1
3 S4
4 S2
6 S5
8 S6
9 S3
Fig. 1
2. The keys 12, 18, 13, 2, 3, 23, 5 and 15 are inserted into an initially empty hash table of length 10 using open addressing with hash function
h(k) k mod10 and linear probing. What is the resultant hash table?
0 0 0 0
1 1 1 1
2 2 2 12 2 12 2 12, 2
3 23 3 13 3 13 3 13, 3, 23
4 4 4 2 4
5 15 5 5 5 3 5 5,15
6 6 6 23 6
7 7 7 5 7
8 18 8 18 8 18 8 18
9 9 9 15 9
4.
Consider a hash table of size 11 that uses open addressing with linear probing. Let h(k)
k mod11be a hash function used. A sequence of
records with keys
43 36 92 87 11 4 71 13 14
www.padeepz.n 1
www.padeepz.n
et
is inserted into an initially empty hash table, the bins of which are indexed from zero to ten. What is the index of the bin into which the last record
is inserted?
(A) 3
(B) 4
(C) 6
(D) 7
5.
The minimum number of comparisons required to determine if an integer appears more than n/2 times in a sorted array of n integers is
(A) (n)
(B) (log n)
(C) (log* n)
(D) (1)
6.
Consider a hash function that distributes keys uniformly. The hash table size is 20. After hashing of how many keys will the probability that any new
key hashed collides with an existing one exceed 0.5.
7.
Consider a hash table of size seven, with starting index zero, and a hash function (3x + 4) mod 7. Assuming the hash table is initially empty, which of
the following is the contents of the table when the sequence 1, 3, 8, 10 is inserted into the table using closed hashing? Note that – denotes an
empty location in the table.
(A) 8, ‐, ‐, ‐, ‐, ‐, 10
(B) 1, 8, 10, ‐, ‐, ‐, 3
(C) 1, ‐, ‐, ‐, ‐, ‐, 3
(D) 1, 10, 8, ‐, ‐, ‐, 3
8.
A hash table contains 10 buckets and uses linear probing to resolve collisions. The key values are integers and the hash function used is key % 10. if
the values 43, 165, 62, 123, 142 are inserted in the table, in what location would the key value 142 be inserted?
9.
A program P reads in 500 integers in the range [0, 100] representing the scores of 500 students. It then prints the frequency of each score above 50.
what would be the best way for P to store the frequencies?
10. Two matrices M1 and M2 are to be stored in arrays A and B respectively. Each array can be stored either in row‐major or column‐major order in
contiguous memory locations. The time complexity of an algorithm to compute M1 × M2 will be
11.
An advantage of chained hash table (external hashing) over open addressing scheme is
12.
Consider a hash table with chaining scheme for overflow handling:
(i) What is the worst‐case timing complexity of inserting n elements into such a table?
www.padeepz.n 2
www.padeepz.n
(ii) For what type of instances does this hashing scheme take the worst case time for insertion?
et
13.
Let A be a n x n matrix such that the elements in each row and each column are arranged in ascending order. Draw a decision tree which finds 1st,
2nd and 3rd smallest elements in minimum number of comparisons
14.
An array A contains n integers in locations A[0], A[1], ..,
‐ A[n‐1]. It is required to shift the elements of the array cyclically to the left by K places, where
1 ≤ K ≤ n‐1. An incomplete algorithm for doing this in linear time, without using another array is given below. Complete the algorithm in the blanks.
Assume all variables are suitably declared.
min: = n;
i: = 0;
while do
begin
temp: = A[i];
j: = i;
while do
begin
A[j]: = ;
j: = (j+K) mod n;
min: = j;
end;
i: =....................;
end;
15.
An array A contains n integers in non‐decreasing order, A[1] ≤ A[2] ≤ ….≤ A[n]. Describe, using Pascal‐like pseudo code, a linear time algorithm to
find i, j such that A[i] + A[j] = a given integer M, if such i, j exist.
16.
A two dimensional array A[1..n][1..n] of integers is partially sorted if
The smallest item is deleted. Complete the following O(n) procedure to insert item x (which is guaranteed to be smaller than any item in the
last row or column) still keeping A partially sorted. (4)
var i, j: integer;
begin
www.padeepz.n 3
www.padeepz.n
(7)
(8) end
et
(9) A[i][j]:=
end
17.
Let A be a two dimensional array declared as follows:
Assuming that each integer takes one memory locations the array is stored in row‐major order and the first element of the array is stored
at location 100, what is the address of element A[i][j]?
18.
Suppose you are given an array s[1 .. n] and a procedure reverse(s, i, j) which reverses the order of elements in s between positions i and j (both
inclusive). What does the following sequence do, where 1 ≤ k < n
19.
Consider the following declaration of a two dimensional array in C:
Char a[100][100];
Assuming that the main memory is byte addressable and that the array is stored starting from address 0, the address of a[40][50] is
A. 4040
B. 4050
C. 5040
D. 5050
www.padeepz.n 4