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

Data Structure

The document discusses data structures and stacks. It defines data structures as ways to organize data so that operations can be performed efficiently. Data structures can be linear (arrays, stacks, queues, linked lists) or non-linear (trees, graphs). Stacks follow the last-in, first-out principle and have push and pop operations. Stacks can be implemented using arrays or linked lists. The document provides code examples for stack abstract data types and implementations.

Uploaded by

Sarwesh Maharzan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

Data Structure

The document discusses data structures and stacks. It defines data structures as ways to organize data so that operations can be performed efficiently. Data structures can be linear (arrays, stacks, queues, linked lists) or non-linear (trees, graphs). Stacks follow the last-in, first-out principle and have push and pop operations. Stacks can be implemented using arrays or linked lists. The document provides code examples for stack abstract data types and implementations.

Uploaded by

Sarwesh Maharzan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

iBiratPUSL http://pu.ibirat.

com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Data Structure
It is a wave to organize the data in some way so we can do the operations on these
data in effective way. Data structure may be organized in many different ways. The logical
or mathematical model of a particular organization of data is called data structure. Choice
of data model depends on two considerations.
It must be rich enough in structure to mirror the actual relationship of the data in
the real world.
The structure should be simple enough that one can effectively process the data
when necessary.

Data structure can be classified as:-


1. Linear data structure:-
Processing of data items by linear fashion is linear data structure e.g. array, stack,
queue, linked list.
In case of stack:- -Last input is the first output i/p
1 input process is called push. o/p
2 Output process is called pop.
In case of queue - First input is the first output.
3 Input is called rear.
4 Output is called front.
In case of linked list

start

info info
info mation mation
First part consists of information and second part consists of pointer to second
block.

2. Non Linear data structure:-


A data structure in which insersion and deletion is not possible in a lnear
fashion is called non –linear data structure. E.g. tree, graph.

Powered by iBirat Technologies <http://www.ibirat.com> 1


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

student

Student_Id Name address Branch

street BE BCA BIT


F_name L-name area

Comput er
Ele ctro
nices

5 It is hierarchial in nature.

Graph:-
Nepalgunj
Illam

Kathmandu

Biratnagar Birgunj

fig. airlines flights

- Contents relationship between pair of elements which is not in hierarchial


in nature.

3. Abstract Data type (ADT):-


ADT is used to specify the logical properties of the data type. It is a set of operation
which is called with the component of the element of that abstract data type.
e. g. list as ADT the term ‘ADT’ refers to basic mathematical
Component concept that defines the data type.
Item
Operations
-Insertion
- Deletion
- Search
- Display
Here, item is component of ADT.
An ADT consists of two parts.
(a) value definition

Powered by iBirat Technologies <http://www.ibirat.com> 2


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

i. Definition clause
ii.Condition clause
(b) operator definition
# ADT for Relation :-
/*value of definition */
Abstract type def <integer, integer> RTIONAL // value definition
Condition RATIONAL [1] = 0; // deonominator is not equal to zero; condn.
/* operator definition * /
Abstract RATIONAL make rational (a, b)
Int a,b;
Percondtion b! = 0;
Post condition make rational [0] == a;
Make rational [1] == b;
Abstract RATIONAL add (a, b)
RATIONAL a,b;
Past condition add [1] == a[1] * b[1];
Add [0] == a[a] * b[1] + b[0] * a[1];
Abstract RATIONAL mult (a,b)
RATIOANL a, b;
Post condition mult [0] ==a[a] * b[0];
Mult [1] == a[1] *b[1];
Abstract RATIONAL equal (a,b)
RATIONAL a,b;
Post condition equal == (a[0] * b[1] == b [0] * a[1]);

Goals of data structure:-


Data structure involves two complementary goals:-
(1) identify and develop useful mathematical intities and operations and determine
what class of problems can be solved by using these entities and operations.
(2) Determine representation fro those abstract intities and implement the abstract
operations on these concrete representations.
Properties of Data structure:-
6 Generalization:-

Powered by iBirat Technologies <http://www.ibirat.com> 3


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Entity generalizes the primitive data type (integer, real, float)


7 Encapsulation:-
All the operation of that type can be localized to one section of program.

Chapter:- 2

Stack:- Stack is an ordered collection of items in to which new items may be inserted
and from which items may be delete at one ene, called tope of the stack.
Two operations aer possible on stack:-
(1) push:- Add item in to stack.
(2) Pop :- delete the item from stack.

C
B B B D
Top =-1 A A A A A A A
(a) Empty (b) Push A (c ) Push B (d) Push C (e) Pop C (f) Pop B (g) Pus D (h) Pop D

From figure we see that the items inserted at last is the first item to be poped or
deleted. Thus stack follows last in first out (LIFO) or first in last out (FILO) policy.
Stack of ADT:-
Abstract typedef << dtype>> STACK(dtype); //define datype stack type element)
Abstract empty (s) // for empty function.
STACK (eltype) s;
Past condition empty == (len(s)== 0); // condition for empty.
Abstract eltype pop (s) //function declearation.
STACK (eltype ) S; // variable declearation.
Precondition empty (S)== FALSE; //condition for fulfill.
Past condition pop == first (S’); /length in pree condition.
S== subh(S”,1, len(S’)-1); // S’- original length, 1- deleting item,
len(S)1- post condition .-push
abstract push (S, elt) // add new element elt.
STACK (eltype) S; // new variable declearation.
Post condition S== <elt>+S’; //

Powered by iBirat Technologies <http://www.ibirat.com> 4


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Stack Implementation:-
(i) Array implementation
(ii) Linked list.

Array Implementation:-
In Array we can push elements one by one from 0th position 1st position …….. n-1th
position. Any element can be added or deleted at any place and we can push or pop the
element from the top of the stack only.
1. When there is no place for adding the element in the array, then this is called stack
overflow. So first we check the value of top with size of array.
2. When there is no element in stack, then value of top will be -1. so we check the
value of top before deleting the element of stack.
5 10 15
Stack_array [0] [1] [2] [3] [4] [5] [6]

Here, Stack is implemented with stack array, size of stack array is 7 and value of top is 2.
Operation of Stack:-
Push Operation:-
If (top == (max-1)]
Printf(“stack over flow”);
Else
{
Top == top + 1;
Stack_arr[top] = pushed –item;
}
Pop Operation:-
If (top ==-1)
Printf(“stack underflow”);
Else
{
Printf(“Poped element is %d”,stack_arr[top]);
Top= top – 1;
}

Powered by iBirat Technologies <http://www.ibirat.com> 5


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Algorithm for push & Pop


PUSH:-
Let stack [Max size] is an array for implementing the stack
1. [check for stack overflow?]
If top = maxsize-1, then print overflow & exit
2. set top = top + 1 (increase top by 1)
3. set stack [top] = item (inserts item in new top position )
4. exit.

POP:-
1. check for the stack underflow
If Top <0 then
Print stack underflow and exit
Else
[Remove the top element]
Set item = stack [ top]
2. Decrement the stack top.
3. Return the deleted item from the stack.
4. Exit.

Application of Stack:-
1 Conversion of an expression from infix to post fix.
2 Evaluation of an arithmetic expression from post fix expression.

Precedence:-
$ (POwre), %(remainder) -5
*(mu), /(div) - 4
+ (add), -(sub) -3
( -2
) -1

Conversion of Infix to post fix:-


Algorithm:-

Powered by iBirat Technologies <http://www.ibirat.com> 6


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

1. Add a unique symbol # in to stack and at the end of array infix.


2. Scan symbol of array infix fro left to right.
3. If the symbol is left parenthesis ‘(‘ then add in to the stack.
4. If symbol is operand then add it to array post fix.
5. (i) If symbol is operator then pop the operator which have same precedence or
higher precedence then the operator which occurred.
(ii) add the popped operator to array post fix.
(iii) Add the scaned symbol operator in to stack.
6. (i) If symbol is right parenthesis ‘)’ then pop all the operators from stack until left
parenthesis ‘(‘ in stack.
(ii) Remove left parenthesis ‘(‘ from stack.
7. If symbol is # then pop all the symbol form stack and add them to array post fix
except #.
8. Do the same process unitl # comes in scanning array infix.

Change Infix to post fix:-


Q. 1. A + B – C + D
1 A+ B – C + D #
Step Symbol Operator in stack post fix expression
1 A # A
2 + #- A
3 B #+ AB
4 - #- AB+
5 C #- AB+ C
6 + #+ AB +C -
7 D #+ AB + C -D
8 # # AB+C-D+

Q.2.A* (B+C $D) – E $F * (G/H)


A*(B+C$D) – E$ F*(G/H)
Step Symbol Operator in stack post fix expression
1 A
# A

Powered by iBirat Technologies <http://www.ibirat.com> 7


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

2 *+ #* A
3 ( #+ AB
4 B #- AB+
5 + #- AB+ C
6 C #+ AB +C -
7 $ #+ AB + C -D
8 D # AB+C-D+
9 ) #* ABCD $+
10 - #- ABCD$+*
11 E #- ABCD$+*E
12 $ #-$ ABCD $ + *E
13 F #-$ ABCD$ +*EF
14 * #-* ABCD$ +*EF$
15 ( #-*( ABCD$+*EF$
16 G #-*( ABCD$+*EF$G
17 / #-*(/ ABCD$+*EF$G
18 # #-*(/ ABCD$+ *EF$GH/
19 ) #-* ABCD$ +*EF$GH/*-
20 # # ABCD$+*EF$GH/*-

Hence, the required post fix expression is ABCD$ +* EF $ GH/*-

Evaluation of post fix expression:-


In this case stack contents the operands. In stead of operators. Whenever any
operator occurs in scanning we evaluate with last two elements of stack.
Algorithm:-
(i) Add the unique symbol # at the end of array post fix.
(ii) Scan the symbol of array post fix one by one from left to right.
(iii) If symbol is operand, two push in to stack.
(iv) If symbol is operator, then pop last two element of stack and evaluate it as [top- 1]
operator [top] & push it to stack.
(v) Do the same process until ‘#’ comes in scanning.
(vi) Pop the element of stack which will be value of evaluation of post fix arithmetic

Powered by iBirat Technologies <http://www.ibirat.com> 8


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

expression.

Postfix expression ABCD $+* EF$GHI * -


Evaluate postfix expression where A = 5, B = 5, C = 4, D = 2 E = 2, F= 2 , G = 9, H= 3
now, 4, 5, 2, $ , +, *, 2, 2, $, 9, 3, /, *, - , #
Step Symbol Operand in stack
1 4 4
2 5 4, 5
3 4 4,5,4
4 2 4,5,4,2
5 $ 4,5,16
6 + 4,21
7 * 84
8 2 84,2
9 2 84, 2,2
10 $ 84,4
11 9 84,4,9
12 3 84,4,9,3
13 / 84, 4, 3
14 * 84,12
15 - 72

The required value of postfix expression is 72


For checking:-
A*(B+C$D) – E$F*(G/H)

4*(5+42)-22*(9/3 )
4* (5+16)-4*3
84-12
72

Q. Convert the post fix:-


((A+B)*C – (D-E) 4F+G
Evaluate post fix where A=1, B=2, C= 3, D= 4, E= 3, F=2, G=1.

Powered by iBirat Technologies <http://www.ibirat.com> 9


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Verify it by evaluating it’s infix expression.


Step Symbol Operand in stack Post fix operation
1 ( #(
2 ( #(( A
3 + #((+ A
4 B #((+ AB
5 ) #() AB+
6 * #(* AB+
7 C #(* AB+C
8 - #(- AB+C*
9 ( #(-( AB+C*
10 D #(-(- AB+C*D
11 - #(-(- AB+C*D
12 E #(-(- AB+C*DE
13 ) #(- AB+C*DE-
14 ) # AB+C*DE--
15 $ #$ AB+C*DE--
16 ( #$( AB+C*DE--
17 F #$( AB+C*DE - -f
18 + #$(+ AB+C*DE--f
19 G #$(+ AB+C*DE - - FG
20 ) # AB+C*DE- - FG+ $
The required postfix expression is AB+C*DE - - FG +$
Now 1,2, +3, *4, 3, -, -, 2, 1, +, $, #
Step Symbol Operand in stack
1 1 1
2 2 1,2
3 + 3
4 3 3,3
5 * 9
6 4 9,4
7 3 9,4,3,1
8 - 3,1

Powered by iBirat Technologies <http://www.ibirat.com> 10


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

9 - 8
10 1 8,2
11 1 8,2,1
12 $ 8,3
13 $ 24
For checking
The given infix expression is
((A+B)*C-(D-e))$(F+G)
= ((1+2)*3-(4-3))4(2+1)
= (3*3 -1) $3
= (9-1)$3
=8$9
= 24

Chapter:- 3
Queue:-
A queue is an ordered collections of items from which items may be deleted at one
end called the front of the queue and in to which items may be inserted at the other end
called rear of the queue.
Deletion Insertion
Front rear
e.g.
queue – arr [5] [0] [1] [2] [3] [4]

front =-1 (a) empty queue.


Rear =-1

Front =0 fig:- adding an item in queue


Rear =0

Front =0
Rear =1 fig:- adding an item in queue.

Powered by iBirat Technologies <http://www.ibirat.com> 11


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Front = 1 fig:- deleting an element from queue


Rear =2

Front = 1
Rear = 3 fig:- adding an element in queue
from figure we see that item are inserted at rear end and deleted at front end. Thus
queue follows FIFO policy. (First in first out).

Queue as an A-DT
Abstract tyupedef <<eltype>>QUEUE (eltype); //queue type element.
Abstract empty (q)
QUEUE (eltype) q;
Post condition empty = = (len (q) = =0);
Abstract eltype delete (q)
QUEUE(eltype ) q;
Pre condition empty (q) = = FALSE
Post condition remove = = front (q’);
q = = sub(q’, 1, len(q’-1);
abstract insert (q, elt)
QUEUE (eltype) q;
Eltype elt ;
Post condition insert = rear (q’);
Q = q’+<elt>;

Queue Implementation :-
8 array implementation
9 linked list implementation
Array implementation of Queue:-
A queue top two pointers front and rear pointing to the fornt and rear element of
the queue.
- when there is no place for adding elements in queue, then this is called queue overflow.
- when there is no element for deleting from queue, then value of front and rarer will be -1
or front will be greater then rarer.

Powered by iBirat Technologies <http://www.ibirat.com> 12


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

[0] [1] [2] [3] [4]

Fron t =1
Rear =1
Operation in queue
1. Add operation :-
If (rear = = Max -1)
Printf(“queue overflow”);
Else
{
If (front = = -1)
Front = 0;
Rear = rear + 1;
Queue_arr[rear]= added-item;
}
Delete operation:-
If (fornt = = -1)|| (front >rear)
{
Printf(“Queue under flow”);
Return;
}
Else
Printf(“Element detected from queue”, queue_arr[fornt]);
Front = fornt +1;
}
Drawbacks:-
[0] [1] [2] [3] [4]

Front =2
Rear = 4
Here we see that the rear is at the last position of array and front is not at the zero th
position. But we can not add any element in the queue because the rear is at the n-1
position.
There are two spaces for adding the elements in queue. But we can not add any

Powered by iBirat Technologies <http://www.ibirat.com> 13


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

element in queue because are is at the last position of array. One way is to shift all the
elements of array to left and change the position of front and rear but it is not practically
good approach. To overcome this type of problem we use the concept of circular queue.

Algorithm to insert an element in a queue Deletion


Step:-1 Step:-1
[check overflow condition] [check underflow condition]
If rear (=) > [Max -1] if front =-1
o/p :”over flow” o/p:”underflow & return;
return;
Step:-2 Step:-2
[increment rear pointer] Remove an element
Rear = rear +1 value: Q[Front]
Step:-3 Step:-3
[insert an element ] [check for empty queue]
Q[rear]= value if front = = rear
Front =-1
Step:-4 Rear = -1
[set front pointer] else
If front =-1 front = front +1
Step:-5 Step:-4
Return Return [value]

Circular Queue:-
[0] [1] [2] [3] [4]

A circular queue is one in which the insertion of new element is done at the very first
location of the queue if the last location of the queue is full.

Powered by iBirat Technologies <http://www.ibirat.com> 14


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

n-1
0

1
4
3 2

fig. CIrcular queue


e.g consider C queue_arr[4]
a. [0] [1] [2] [3]
froom = 1 rear = 3.
initial queue
b. [0] [1] [2] [3]
front = 2
fig. deletion in queue rear = 3
c. front =0
rear = 1
fig. additon in queue.
d rear =1
front =2
fig. addition in queue.
e front =1
rear = 3
fig. deletion in queue.
f front = 1
rear =1
fig. deletion in queue

g front = 1
rear =1
fig. deletion in queue
h rear = 1
front =-1

Powered by iBirat Technologies <http://www.ibirat.com> 15


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

fig. deletion in queue

Insersation:-

If ((front == 0 && rear = Max -1 ) || (front = = rear +1))


{
Printf(“Queue overflow”);
Return;
}
If (fornt = = - 1)
{
Front =0;
Rear = 0;
}
Else
If(rear == Max -1)
Rear =0;
Else
Rear = rear +1;
(queue_arr[rear] = added_item;

Operation
Deletion:-
If (front = = -1
{ printf(“queue underflow”);
Return;
}
Else
Printf(“element delected from queue is %d”);
(queue_arr[front];
If (front == rear)
{

Powered by iBirat Technologies <http://www.ibirat.com> 16


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Fornt =-1;
Rear = -1;
}
Else
If (fornt = = Max – 1)
Front = 0;
Else
Front = front +1;
Dequeue (Double ended queue)
In dequeue we can add or delete the element from bothsides i.e. front end or form
the rear end. It is of two types.
(i) I/P restricted
(ii) O/P
In input restricted dequeue element can be added at only one end but we can delete
the element from both sides.
In output restricted dequeue eleme4tn can be added from both side but deletion is
allowed only at one end.

Operation in Dequeue:-
We assume a circular array fro operation of addition or deletion.
[0] [1] [2] [3] [4] [5] [6] [7]

Left = 2
Right = 4
We maintain two pointers right & left which indicate positions of dequeue. Here, left
pointer is at position 2 and right pointer is at position 4.
For I/P restricted:-
(i) Add 8 in the queue from right.

(ii) Delete the element from left of the queue

(iii) Add the element 20 in the queue

(iv) Add the element is in queue

Powered by iBirat Technologies <http://www.ibirat.com> 17


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

(v) Delete the element form right of queue.

(vi) Add the element 80 in the queue

(vii) Add the element 12 in the queue.

(viii) Add the element 35 in the queue.

(ix) Add the element 5 in the queue.

(x) Add the element 45 in the queue. No it overflows because right pointer will

become equal to the left pointer after adding an element.

Right addition:-
If(left = = 0 && right == Max -1) || (left = = right +1))
{
Printf(“Queue overflow”);
Return;
}
If (left==-1)
{
Left =0;
Right =0;
}
Else
If (right = = Max -1)
Right = 0;
Else
Right = right +1;
Dedequeue_arr[right] = added_item;

Left Addition:-
If (( left == 0 && right == Max-1) || (left == right +1))

Powered by iBirat Technologies <http://www.ibirat.com> 18


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

{
Printf(“Queue overflow”);
Return;
}
If (left==-1)
{
Left =0;
Right =0;
}
Else
If (left == 0)
Left = Max -1;
Else
Left = left -1;
Dequeue_arr[left] = added_item;

Delete left:-
If (left==-1)
{
Printf(“Queue flow”);
Return;
}
Printf(“Element deletd from queue is “%d”, dequeue_arr[left]. // point delete item
If (left == right ) // make empty
{
Left ==-1;
Right =-1;
}
Else
If(left== Max -1) //move from zero.
Left =0;
Else
Left = left +1; // increase space.

Powered by iBirat Technologies <http://www.ibirat.com> 19


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Delete Right:-
If (left ==-1)
{
Printf(“Quieue underflow”);
Return;
}
Printf(“element delected from queue is %d”, deque_arr[right]);
If(left==right)
{
Left =-1;
Right =-1;
}
Else
If(right==0)
Right =Max-1;
Else
Right = right [-1;
}

Chapter:- 4
A linear list is an ordered set consisting of a umber of elements to which addition
w& deletion can be made. A linear list displays the relationship of physical adjenu. The first
element of a list is called the hear of list & the last is called the tail of the list. The next
element of the head of the list is called it’s successes. The previous element to the tail (if it
is not head of the list) is called it’s predessor. Clearly a head doesn’t have as predessor & a
tail doesn’t have a successor. Any other element of the list has both one successor & one
predessor.

Powered by iBirat Technologies <http://www.ibirat.com> 20


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

head
Operations perform in list:-
(i) Traversing an array list
(ii) Searching an element in the list
(iii) Insertion of an element in the list
(iv) Deletion of an element in the list.
Array Implementation:-
Take an array of size 10 which has 5 elements
[0] [1] [2] [3] [4 ] [5] [6] [7] [8] [9]

Traversing an array list:-


Here each element can be found through indeed no. of array & is incremented by 1.
When index =0.
Then,
Arr[10] = 10 determines 1st element in array
Index = index +1
Then
Arr[index]= 20
In this way we can transverse each element of array by incrementing the
index by 1 until index is not greater than no. of elements.

Searching in an array list:-


For searching an element, we first travers the array list and while traversing , we
compare each element of array with the given element.
Int I, item;
For (i=0;i<n;i++)
‘{
If(item== arr[i])
Return(i+1);
}
Insertion of an element in the list:-
-two ways:-

Powered by iBirat Technologies <http://www.ibirat.com> 21


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

(i) insertion at end


(ii) insertion in between.
Insertion at end

60 element inserted at 6th position


Set the array index to the total no of elements & then insert the element
Index = Total no of element (i.e 5)
Arr[index] = value of inserted element

60 element inserted at 4th position


Shift right one position all array elements from last array element to the array
element before which we want to insert the element.
Int tem, item, position;
If (n = = max)
{
Printf(“list overflow”);
Return;
}
If (position >n+1)
{
Printf(“enter position less than or equal to %d”n+1);
Return;
}
If(position = = n+1) /*insertion at the end */
{
Arr [n]= item;
N= n+1;
Return;
}
Temp = n-1 //insertion in between
While (temp>=positon-1)
{
Arr[temp+1] = arr [temp];
Temp - -

Powered by iBirat Technologies <http://www.ibirat.com> 22


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

}
Arr [positon -1] = item;
n = n+1;
Deletion of an element in the list:-
(i) deletion of the last element
(ii) deletion in between
(iii) Deletion of the last element:-

Deleted element
Transvere the array last and if the item is last item of the array, then delete that
element & decrease the total no of element by 1,
(ii) Deletion in between:-

Deleted element
First traverse the array list & compare array element with the element which is to be
deleted, then shift left one position from the next element to the last element of
array and decrease the total no. of elements by 1.
Int temp, position , item, n;
If (n= = 0) // present or not element
{
Printf(“list underflow”);
Return;
}
If (item == arr [n-1] //deletion at the end.
{
n = n- 1;
return;
}
Temp = position -1;
While (temp < = n -1)
{
Arr [temp] = arr [temp +1]
Temp + + ;

Powered by iBirat Technologies <http://www.ibirat.com> 23


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

}
n = n -1;

Advantage of list:-
Easy to compute the address of the array through index 4 can be access the array
element through index.
Disadvantage:-
Use of contiguous list which is time consuming.
As array size is declared we can’t take elements more then array size.
If the elements are less than the size of array, then there is wastage of memory.
Too many shift operation on each insertion and deletion.

To overcome this problem we use liked list or DLL.

Index to prefix conversion :-


Rules:-
1. Parenthesize the expression starting from left to right.
2. During parenthesizing the expression, the operands associated with operator having
higher precedence are first parenthesized.
e.g. B * C is first parenthesized before A+B in A+B *C
3. the sub expression which has been converted in to prefix is to be treated as single
operand.
4. once the expression is converted to postfix from remove the parenthesis.

Question:- (A*B + (C/D) –F


(A*B + (C/D) –F
((A*B + (C/D)) – F)
((A*B+W) – F) [ W = /CD let]
(( *AB + W) –F)
((X +W)-F [ X = *AB]
(+XW – F)
(Y –F) [ Y = +XW
-YF

Powered by iBirat Technologies <http://www.ibirat.com> 24


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

-+XWF
- + ABWF
- + * AB/CDF.
Which is required prefix expression.

Dynamic memory allocation:-


In an array it is necessary to declare the size of array. This creates two possible
problems.
(i) If the records that are stored is less than the size of array, then there is a
wastage of memory.
(ii) If we want to store more records then size of array, we can’t store.

To overcome these problem we use dynamic memory allocation. The functions used
for dynamic memory The functions used for dynamic memory allocation and deallocaton
are :-
(i) Malloc()
(ii) Calloc()
(iii) Free()
(iv) Realloc()
Malloc():-
This function is used to allocate memory space. The malloc () function reserves a
memory space of specified size and gives the strating address to the pointer variable.
Syntax:-
Ptr = (data type * ) malloc (specified size)

Type of pointer size required to reserve in memory.

Example:-
Ptr = (int *) malloc (10);
Struct student
{
Int roll_no;
Char name [30];

Powered by iBirat Technologies <http://www.ibirat.com> 25


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Float percentage;
};
Struct student * st_ptr.
St_ptr = (struct student *) malloc size of (struct student);
Calloc():-
The caloc () function is used to allocate multiple blocks of memory. This has two
arguments.
Syntax:-
Ptr = (data type *) calloc (memory block, size )
Example:-
Ptr = (int * ) calloc (5, 2)
Struc record
{
Char name [10];
Int age;
Float sal;
};
Int to_record =100;
Ptr = (struct record *) calloc (tol_record, size of (record));

Free():-
This function is used to deallocate the previously allocated memory using mulloc ()
or calloc() function .
Syntax:-
Free (ptr);
Realloc():-
This function is used to resize the size of memory block which is already allocated. It
is used in two condition.
If the allocated memory block is insufficient for current application.
If the allocated memory is much more thasn what is required by the current
application.

Syntax:-

Powered by iBirat Technologies <http://www.ibirat.com> 26


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

To allocate memory; we use


Ptr = (char *) mallc(6);
To reallocate memory;
Ptr = (char * ) realloc (ptr, B)

Chapter:- 5
A link list is a collection of elements called nodes each node hap two parts, 1 st part
contains the information field & the 2nd part contains the address of the next node. The
address part of the last node of linked list will have null value.
information
linked

null
address part of the node which contains
the address of the next node.
Infro. Part of the node.
In liked list one member is a pointer that points to a structure itself.
Syntax:-
Struct node
{
Int data;
Struct node * link;
};
Here, member of the structure struct node * link points to the structures itself.
Implementation:-
Traversing a linked list:-
In liked list start is a pointer which points to the 1 st element of the list for processing
next element we assign the address of the next element to the pointer (ptr) as:
Ptr = ptr – link;
Each element of the liked list can travel through this assignment until ptr has null address.
So, the linked list can be traversed as:-
Which (ptr ! = NULL)

Powered by iBirat Technologies <http://www.ibirat.com> 27


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Ptr = ptr – link;


Searching in to a linked list:-
For searching the element first traverse the linked list and with traversing compare
the information part of each element with the given element it can be written as:
While (ptr!=NULL)
{
If (ptr info = = data)
Printf(“Item %d found at position %d”, data, pos);
Else
Ptr = ptr link;
Insertion in to a linked list:-
Insertion at beginning
Insertion in between

NULL

temp
Here, temp is a pointer points to the node that has to be inserted ie.
Temp infro = data;
Start points to the 1st elements of linked list for insertion at beginning we assign the
value of start to the linked part of the inserted node as
Temp infro = start; and start can be re assigned as
Start = temp;

Insertion in between:-

a NULL

Powered by iBirat Technologies <http://www.ibirat.com> 28


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

TEMP
First we traverse the linked list for obtaining the node after which we want to insert
the element. We obtain pointer 9 which points to the element after which we have to
insert new node. For inserting the element after the node, we assign link part of that node
to the link part of inserted node & the address of the inserted node is placed into the link
part of the previous node. This can be written as
Temp infro = data;
Temp link = q link;
q link = temp;
Deletion in to a linked list:-

TEMP
Here, start points to the 1st element of linked list. If element to be deleted is the 1st
element of linked list then we assign the value of start to temp as
Temp = start;
10 temp points to the 1st node which has to be deleted & assign link part of the deleted
node to start as
start = star – link
Since start points to the 1st element of linked list so, start link will point to the
second element of linked list,l now we free the element to be deleted. ie.
Free (temp)
Deletion in between:-

Powered by iBirat Technologies <http://www.ibirat.com> 29


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

If the element is other then the 1st element of linked list then we give the link part of the
deleted node to the link part of the previous node & is given by
Temp = q link;
q link = temp link
Free (temp);
If the node to be deleted is last node of linked list then we can write
Temp = q link;
q link = NULL;
Free (temp);
Stack implementation using linked list:-

Null

temp

Push operation:-
For pushing the element on stack we follow the insertion operation of linked list. i.e.
we add the element at the start of the list this can be written as
Temp = q link = pushed item;
q link = top;
top = temp;
Here, top always points to the 1st node of the linked list. Last pushed item will become 1st
node of linked list. As there is use of linked list we don’t check overflow condition.

Pop operation:-

temp
For this we delete the first element of linked list.

Powered by iBirat Technologies <http://www.ibirat.com> 30


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

If (top = = NULL)
Printf(“Stack is empty”);
Else
Temp = top;
Printf(“popped item is %d”, temp info);
Top = top link;
Free(temp);

Queue implementation using linked list:-

null

For adding the element in queue, we add the element at the end of the list. Here,
front will point to the 1st node of the linked list & rear will point to the last node of the
linked list this can be written as
Temp info = added_item;
Temp link = NULL
If (front == NULL)
Front = temp;
Else
Rear link = temp;
Rear = temp;
Deletion operation :-
For deleting the element of a queue we delete the 1st node of linked list .

Temp

If (fornt = = NULL)

Powered by iBirat Technologies <http://www.ibirat.com> 31


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Printf(“queue underflow”);
Else
{
Temp = fornt;
Printf(“Deleted element is %d”, temp info);
Front = front link;
Free (temp);
};
Double linked list (DLL):-
In single linked list we can traverse only in one direction because each node has
address of next node only. Suppose we are in the middle of linked list & we want ot to
operation with just previous node, then we have no way to go in previous node. And
we’llain traverse from starting node which is time consuming./ To overcome this problem
we use double linked list.
In DLL each node has address of previous & next node along with data.

Null info. Part of node contain add. Of previous node null

Contain add. Of next node


Each node has to contain the address of information of previous node. The data structure
for DLL is
Struct node
{
Struc node * previous;
Int info;
Struct node * next;
}
Here, struct node * previous is pointer to structure which will contain the address of
previous node & struct node * next will contain the address of next node in list. Thus we can
travel in both the direction.

Powered by iBirat Technologies <http://www.ibirat.com> 32


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Operation
1. Traversing a double linked list:-
Start points to the 1st element of the list and we assign the value of start to ptr so ptr so
ptr points to the 1st noe dof the list. For processing the next element we assign the
address of next node to ptr as
Ptr = ptr next
Now, ptr has address of next node. Thus, we can traverse each element of list through
this assignement until ptr has null value which the next part value of last element . it can
traverse as:
While (ptr!= NULL)
Ptr = ptr next;

2. Insertion:-
(a) Insertion of beginning:

For insertion at beginning we assign the value of start to tehnext part of inserted node
and address of inserted node to the previous part of stat as:
temp next= start;
start prev = temp
now, inserted node points to the next node which is beginning node of DLL and ‘prev’
part of second node will point ot ht new inserted node. Now inserted node is the first
node of DLL so start will be re assign as
start = temp;
now, start will point to the inserted node which is the 1st node DLL. Assign NULL to the
previous part of inserted node as ‘prev’ node of the first node is null.
Temp prev = NULL.
Thus whole process can re assign as
Temp next = start;

Powered by iBirat Technologies <http://www.ibirat.com> 33


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Start prev = temp;


Start temp;
temp prev = Null.
Insertion in between:-
temp

start

First we traverse the DLL for obtaining the node after which we want to insert the
element. For inserting the element after the node we assign the address of inserted d node
to the ‘prev’ part of next node. Then we assign the next part of previous node to next part
of inserted node. Address of previous node will be assign to pre. Part of inserted node and
the address of inserted node will be assigned to tyeh next part of prevous node. The whole
process can be re assigned as
q next prev = temp;
Temp next = q next;
temp prev = q;
q next = temp;
Deletion
1. Deletion at beginning:-

Temp

Starts points to the 1st node of DLL. It node to be deleted is the4 1st of list then we
assign the value of start to temp as
Temp = start ;
Assign next part of deleted node to start as

Powered by iBirat Technologies <http://www.ibirat.com> 34


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Start = start next;


Since, start points to the 1st node of linked list so start next will point to the second
node of list. Then null will be assigned to start point ot previous.
Start previous = Null
Now, we can free the node to be deleted which is pointed by temp as;
Free(temp)
The whole process can be re assigned as
Temp = start;
Start = start next;
Start prev = NULL
Free (temp)
Deletion in between:-

a temp

If the element is other then the 1st element of linked list then we assign the next
part of deleted node to next part of previous node & address of previous node to ‘prev’ part
to next node this can be written as
Temp = q next; //select node i.e. pointed.
a next prev =q;
temp next prev = q;
free (temp);
deletion of the last node:-
if node to be deleted is last node then we’ll just free the last node & next part of
second last will be null. This can be written as
temp =q next;
free (temp);
q next = Null.

Priority queue:-

Powered by iBirat Technologies <http://www.ibirat.com> 35


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

In priority queue every of queue has some priority and based on that priority it wil
be processed so the element of more priority will be process before the element which has
less priority. If two elements have same priority. Then in this case it follows FIFO policy.
Structure:-
Struct pq {
Int priority;
Int info;
Struct pq * link;
}
Implementation:-
3 info

front
start

1 info 2 info 3 info 4 info

Temp info = added – item


Temp priority = item – priority;
If (front = = NULL || item – priority < front priority)
{
Temp link = front;
Front = temp;
Else
{
While(q link ! = Null && q link priority < = item – priority)
q = q link;
temp link = q link;
q link = temp;
}

Deletion:-
Delete operation wil be the deletion of 1st element of list because it has more

Powered by iBirat Technologies <http://www.ibirat.com> 36


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

priority then other elements of queue.


If (front = = NULL)
Printf(“Queue underflow”))
Else
{
Temp = front;
Printf(“deleted item is %d”, temp info):
Front = front link
Free (temp);
}

Chapter – 6
Recursion :-
Recursion is defined as defining any thing interms of itself. Recursion is usede to
solve problems involving iteration s in reverse order.
Recursive functions:-
1. A function calls itself repeatedly.
2. Recursive program will not continue infinitely. A recursive procedure must have the
following two properties.
a. There must be the certain criteria, called base criteria fro which the procedures
does not call itself.
b. Each time the procedure does call itself, it must be closer to base criteria.
Syntax:-
Main()
{
----------
-----------
Function();
__________
}
Function()
{_____________
Function();

Powered by iBirat Technologies <http://www.ibirat.com> 37


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

}
/* Find factorial of any number */
Main(()
{
Int no, fact;
Printf(“Enter no”);
Scanf(“%d”, &no);
Fact = factl(no);
Printf(“Factorial no = %d”, fact);
}
Int factl(int n)
{
If (n = = 0)
Return(1);
Else
Result = n* fa t (n-1));
Return (result);
}
Output process:-
no =4
result = 24
after every call function will return the value to the previous function
fact l(u) = u* fact l(3)
fact l(3) = 3 * fctl(2)
factl(2) = 1 * fact(0)
fact(0) =1-
Here, steps for calling function are finished new each function will return the value to it’s
previous functions:
Factl(2) = 2 * fact (1) =2
Factl(3) = 3 * fact (2) = 6
` factl(4) = 4 * fct (3) = 4*6 = 24

Fact(1) = 1

Powered by iBirat Technologies <http://www.ibirat.com> 38


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

2 * fact (1) 2 * fact(1) 2 *1 = 2


3*fact(2) 4*fact(3) 4 * fact(2) 3 * fact (2) 3*2 = 6
4*fact (3) 4*fct (3) 4*fact(3) 4*fact(3) 4* factl(3)` 4 * factl(3) 4*6 =24= 24

Need for recursion:-


1. There must be a terminating condition for problem which you want to solve with
recursion. This condition is called the base criteria for that problem.
2. There must be an if condition in the recursion routing, this if clause specifies the
terminating condition for the recursion.
3. Reversal in the order of execution is the characteristic of every recursion. Problem.
4. Every time a new recursive calls is made, a new memory space is allocate to each
automatic variables used by the recursive routine.
5. The duplicated values of the local variables of a recursive call are pushed on to the
stack with it’s respective call & all these value are available to the respective
function when it is popped off from the stack.
Disadvantage:-
1. It consume more storage space because the recursive calls along with automatic
variable are stored in stack.
2. The computer may run out of memory if recursive calls are not cheked.
3. It is not more efficient in turms of speed & execution time.
4. Doesn’t offer any concrete advantage over non recursive functions.
5. If proper precautions are not taken, recursion may result non terminating iterations.

Removal of recursion through iteration:-


Using recursion:-
Int factorial (int no)
{
Int fact = 1;
If (no>1)
Fact = no * factorial (n -1);
Return fact;
Without using recursion:-
Int factorial (int no)
{

Powered by iBirat Technologies <http://www.ibirat.com> 39


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Int fact =1
For(int i=no; i>1;I - -)
Fact = fact * I;
Return fact;
;
Tower of Hanoi (TOH):-
It is a game problem. In this case the disk is moved from one 0pillar to another pillar
with the use of temporary pillar.
Rule:-
11 We can move only one disk from one pillar to another at a time.
12 Large disk can ‘t be can not be placed on smaller disk.
n=2

source temporary destination

n=1 n=3

Step:- I

2
3

Step:- II

1 2 3

Step:- II

3
1 2

Step:- IV

Powered by iBirat Technologies <http://www.ibirat.com> 40


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

3
2 1

Step:- V

3 2 1

Step:- VI

3 1

Step:- VII

3
2
1

Algorithm:-
1. Move upper 0-1 disk from source to temporary.
2. move largest disk from source to destination.
3. move n -1 disk from temporary to destination.

Problem:-
(i) Proc(N -1, S, D, T)
(ii) Proc(1, S, T, D)
(iii) Proc(N-1, T, S, D)]
For n = 1
Proc(1, S, T, D)
Proc(1, S, D, T)
Proc (3, S,T,D) then, proc(2,S,D,T) proc(1,D, S,T)
Proc(1,S, T, D) S D
Proc(2, S, T, D) proc(1, T, D,S)
Proc(1, T, S, D)
Proc(1, T, D, S)

Powered by iBirat Technologies <http://www.ibirat.com> 41


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

proc(1, S, T, D)................ S T

proc(2, S, T, D) proc(1, S, T, D) .................S D


proc(1, T,S, D) ..................T D
proc(3, S, T, D) proc(1, S, T, D) .................................................S T
proc(1,D, T, S) ....................D S
proc(2, S, T, D) proc(1,D, T, S) ......................D T
proc(1, S, T, D) .....................S T

proc(4, S, T, D) proc(1, S, T, D)..........................................................................................S

proc(1,T, S, D) ......................T D
proc(2, S, T, D) proc(1, T, D, S) ......................T S
proc(1, D, T, S) .......................D S
proc(3 , S, T, D) proc(1 , S, T, D)................................... .................T

proc(1 , S, T, D) .....................S T
proc(2 , S, T, D) proc(1 , S, T, D).................... S D
proc(1, T, S, D)......................T D

Translation from prefix to postfix using recursion:-


Algorithm:-
In the prefix string is a single variable, it is it’s own postfix equivalent.
Let operator be the first operator of the postfix string.
Find the first operand opend1, of the string, convert it to postfix call it post 1.
Find the second and 2, conver & call it post 2.
Concatenate post 1, post 2 & op (perand)

Convert into postfix from the given string ** + AB - - + CDEF


Step Symbol operator postfix
1 * OP1
2 * OP2
3 + OP3
4 A Post + AB + post 21
5 B Post 32
6 - OP4
7 + OP5
8 C Post 51 CD + Post 41 post 22

Powered by iBirat Technologies <http://www.ibirat.com> 42


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

9 D Post 52
10 E Post 42
11 F post 12

Chapter :-7
Definition:-
A tree is as non linear data structure in which items are arranged in a sorted
sequence, It is used to represent hierarchial relationship existing among several data items.
Each node of a tree may or may not pointing more than one node.

Theoretic definition of tree:-


It is a finite se of one or more data items (nodep) such that
1. there is a special data item called the root.
2. It’s remaining data items are portioned into no of mutually exclusive subsets, each
of which is it self a tree and they are called sub treep.
A

B C
H
I

E F G M
K
L
J

Fig. Tree

Tree terminology:-
Root:-
The first node in a hierarchial arrangement of data items is root.
Node:-
Each data item in a tree is called a node.
Degree of a node:- It is the no. of subtrees of a node in a given tree from fig.
Here, degree of node A = 3

Powered by iBirat Technologies <http://www.ibirat.com> 43


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Degree of node D = 2
Degree of node F = 1
Degree of node I = 3
Degree of a tree:-
It is the maximum degree of nodep in a given tree here degree of tree is 3.

Terminal node:-
A node with degree 0 is terminal node here, SIGHXLM are terminal node.
Non terminal node:-
Any node except the root whose degree is not zero is call non terminal node.
Siblings:-
The chiblreen nodes of a given parent nodes are called siblings. E and F are siblings
of parent node B and K, L, M are siblings of parents node I & so on.
Level:-
The entire tree structure is leveled in such a way that the root rode is always at level
zero. Then it’s immediate children are at level 1 and there immediate children are at level 2
and so on up to the terminal nodep. Here, the level of a tree is 3.
Path:-
It is a sequence of consecutive edge from the source node to the destination node.
Edge:-
Is it is a connecting line of two nodep i.e. line drawn from one node to another.
Depth or height:-
It is the maximum label of may node in a given tree here, the depth of a tree is 4.
Forest:-
It is a set of disjoint trees. In a given tree if we remove it’s rot then it becomes
forest.
Binary tree:-
A binary tree is a finite set of data items which is either empty or consist of a single
item called the root and two disjoint binary trees the lefts subs tree and right subtree. In
binary tree the maximum degree of any node is almost 2 i.e. each node having 0, 1. or 2
degree node.

Powered by iBirat Technologies <http://www.ibirat.com> 44


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]
A

B
F
G

D E

K L

Strictly Binary tree:-


If every non terminal node in a binary tree consist of anon empty left sub tree and
right sub tree then such tree is called strictly binary tree.
A

B
F
G
E

L I M
N

H
K

Completely binary tree:-


Completely binary tree of depth ‘d’ is the binary tree of depth d that contains
exactly 21` nodep at each level l between zero and d i.e. in a complete binary tree there is
exactly one node at level zero, 2 node at level 1, 4 node at level 2 and so on.

Extended binary tree:- (2-tree)

Powered by iBirat Technologies <http://www.ibirat.com> 45


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

A binary tree is called extended binary tree if every node of tree has zero or two
children. It is called 2- tree.
Algebraic expression representation tree.

a
b

Any algebraic expression can be represented in binary two in which left and right
child represent operand of he expression and parent of the child repressing the operator.
e.g, a + b

Algorithm:-
1 Note the order of precedence. All expression in parenthesis one to be ealuated first.
2 Exponential will come next.
3 Division & multiplication will be the next in order of precedence.
4 Subtraction and addition will be the last to be proceeded.

*C -
+ *

a b d e

*C - ( d *e )
+

a b

Powered by iBirat Technologies <http://www.ibirat.com> 46


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

(a+b)* C – (d * e)

*
*

+ c
d e

a b

* *
`

+ c d e

b
a

(ii) A + (B-C) * D & (E * F) (iii) (A+B*C) & (( B+ B) * C)

A+ - D& *

b c e f

A+ - * &

D *
B C

E F

Powered by iBirat Technologies <http://www.ibirat.com> 47


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

A + *
B

B
B B

B B
B B

A
- &

B
C *
D

F
C

C
B

G H
D
E

Representation of binary Tree:-

Powered by iBirat Technologies <http://www.ibirat.com> 48


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

B C

D E G H

F
Structure:-
Struc node
{
Char data:
Node * lchild;
Node * rchild;
}
Binary Tree Traversal:
While traversing a tree root is denoted by ‘N’ left subtree as ‘R’. Then there will be
six combination of traversal i.e. NRL, NLR, LRN< LNR< RNL & RLN
NLR pre ordered traversal
LAN post order traversal
LNR Inorder
Pre ordered traversal:- NLR
1 Visit the root node.
2 Traverse the left sib tree of root in pre order,”
3 Traverse the right subtree of root in pre order.

Pre order (ptr)


Struct node * ptr;
{
If (ptr ! = NULL)

Powered by iBirat Technologies <http://www.ibirat.com> 49


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

{
Printf(“%d”, ptr data);
Pre order (ptr lchild);
Pre order (ptr rchild);
}}
A
C

B
G

E F
D

Preorder:-
ABDEICFGI
(ii) in order Traversal (LNR)
1 Travere the left subtree of root in order.
2 Visit the root.
3 Traverse the right subtree of root in order.
In order (ptr)
Struct node * ptr;
{
If (pre! = NULL)
{
In order (pre lchild)
Printf(“%C”, ptr data);
In ordre (ptr rchild);
}}
A
C

B
G

E F
D

Post order traversal:- (LRN)


1 Traverse the left subtree of root in post order.

Powered by iBirat Technologies <http://www.ibirat.com> 50


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

2 Traverse the right subtree of root in post order.


3 Visit the root.

Post order (ptr)


Strct node * ptr;
{
If(pt! = NULL)
{
Post order (ptr l child);
Post order (ptr r child);
Printf(“%c”, ptr data);
}
}
Post order:-
DIEBFJGCA

Question:- construct a binary tree from given algebraic expression and show it’s traversals.
(a – b * c ) / (a + e/f)
A- /(a + e/f)

Preorder:-
/ - a * bc + d/e f
Inorder: a–b*/d+e–f
Post order: a b c * - d e f/ + /

Creating the tree from preorder and inorder traversal:-


1 In pre order traversal , scan the nodes one by one and keep them inserting in
tree.

Powered by iBirat Technologies <http://www.ibirat.com> 51


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

2 In order traversal, put the cross mark over the node which has been inserted.
3 To insert a node in it’s proper position in the tree we look at that node the in
order traversal & insert it according to it’s position with respect to the cossed
nodes:-
Preorder:- A B D G H E I C F J K
Inorder:- G D H B E I A C J F K
Step:-1Inset A
Pre: ABDGHEICFJK
Inorder:- GGDHBEIACJFK
Step:-2Inset B
Preorder: ABDGHEICFJK
Inorder:- GDHBEIACIFK
Step:-2Inset D
Preorder: ABDGHEICFJK
Inorder:- GDHBEIACIFK
Step:-3Inset G
Preorder:- ABDGHEICFJK
Inorder:- GDHBEIACIFK
Step:- 4 Inset H
Preorder:- ABDGHEICFJK
Inorder:- GDHBEIACJAK

Step:- 5 Inset E
Preorder:- ABDGHEICFJK
Inorder:- GDHBEIACJFK

Step:- 6 Inset I
Preorder:- ABDGHEICFJK
Inorder:- GDHBFIACJFK

Step:- 7 Inset C

Powered by iBirat Technologies <http://www.ibirat.com> 52


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Preorder:- ABDGHEICFJK
Inordre:- GDHBEIACIFK

Step:- 8 Inset C
Preorder:- ABDGHEICFIK
Inorer:- GDHBEIACICK

Step:- 9 Inset I
Preorder:- ABDGHEICFJK
Inorer:- GDHBEIACIFK

Binary search tree:-


A binary search tree is a binary tree in which each node has value greater than
every node of left sub tree and les than every node of right sub tree.

Question:- construct the binary tree from given data item.


50 30 60 22 38 55 34
50

60
30

38
55

22

34

Construct the binary tree:-


20 17 6 8 10 20 7 18 13 12 5 6

Powered by iBirat Technologies <http://www.ibirat.com> 53


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

20

17

18

5 10

7 13

12

Delete operation in binary tree:-


1 Leaves:- easiest to delete.
- set pointer from it’s parent (if any ) to NULL.
2 Node with one child; fairly easy.
- Replace the node being deleted by it’s in order successor.
e.g
62

75
50
90
60
65

80
85

Delete 85:-
Since 85 has no child rean so, we can delete it., simply by giving NULL value to it’s
parents’ right pointer thus the tree becomes
62

75
50
90
60
65

80

Delete item 50:-


Since, 50 has only one child so we can delete it by giving the address of right child to
it’s parents left pointer thus the tree becomes.

Powered by iBirat Technologies <http://www.ibirat.com> 54


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

62

75
60
90

65

80

Delete items 75:-


In order : 60 62 65 75 80 90
62

80

60 90

65

Since, 75 has two children so 1st we delete the item which is in order successor of 75.
Here, 80 is the in order successor of 75 we delete so by giving NULL value to it’s parents left
pointer after that we replace item 75 with item 80. We give the address of the left and right
pointer of 75 to the left and right pointer of 80 & address of 80 to the right pointer of
parent 75 which is 62. Thus the required tree is shown above.

AVL Tree “Balanced Tree”


“G.M adel’s son, vel’ skill & E.M land is”
A AVL tree is a binary search tree where, height of left & right subtree at any node
will be with maximum difference 1 each node of AVL tree has a balanced factor. Balance
factor of a node is defined as the difference between the left subtree & right subtree of a
node.
i.e. balanced factor = Height of left subtree – height of right sub tree.
A node is called right heavy or right high if height of it’s right sub tree is one more
than height of it’s left sub tree. A node is called left heavy or high if height of it’s left sub
tree is one more than height of it’s right sub tree. A node is called balanced, if heights of left
or right sub tree are equal. The balanced factor will be 1 for for left high & -1 for right high
& 0 for balanced node. Thus in an AVL tree each node can have only three values of balance
factor which are 1, 0 & -1.

Powered by iBirat Technologies <http://www.ibirat.com> 55


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

18

20
15 24

1*9
16

Procedure for insertion of a node in AVL tree:-


1. insert the node at it’s proper place as in binary search tree.
2. Calculate the balanced factors of all the nodes on the path starting from the inserted
nodes to the root node. If the value of balance factor of each node on this path is -1
or 1 then, the tree is balanced. If the balanced factor of nay node is more than 1
than the tree becomes unbalanced . The nod3e which is nearest to the inserted
node 4 has absolute value of balance factor greater than 1, then iit it is marked as
pivot node.
3. If the tree has become unbalanced after the insertion, then the tree is rotated about
the pivot node to achieve all the properties of AVL treep.
AVL rotations:-
1. Left to left rotation:-
15
20
15
24
16
10

12
5

2
1 5 -1

2 2 0
1 5
2 4
0 1 6
1 0
1 1 2
5

Insert 2.
Pivot node:-

If the node is inserted on the left side of left subtree than we perform left to left

Powered by iBirat Technologies <http://www.ibirat.com> 56


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

rotation.
1
18 -1
0 20
10
0
24
1 15
5
16
12
2

2. Right to right rotation:-


15
20
15
35
16
10 38
26

-2
15 -2
1 20
15 -1
35
16 -1
10 38
26
39
Insert 39

If the node is inserted on the right side of right sub tree than we perform right to right
rotation.

18
20
15
24
16
10

12
5

Powered by iBirat Technologies <http://www.ibirat.com> 57


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

15
35
15
38
16
10 39
26
19

3. Left to right rotation:-


If the node is inserted on the right side of left sub tree then we perform left to right
rotation.

In this left to right rotation, the operation involves two steps 1st we perform
right to right from next to pivot node then perform left to left.
1 8
2 0 18
1 5 20
2 4
1 6 12
1 2 24
15
1 4
1 0 10
16
14
5 5

4. Right to left rotation:-


-2
18 -2
1 20
18
15
20 35
15 19
35 10 38
insert 24 26
19
10 38
26
24
-2
18 -2
20
15 -1
26
19 -1
1 35
26

38

5. Rotate right to Right:-

Powered by iBirat Technologies <http://www.ibirat.com> 58


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

18
26
15
35
20
10 38
24
19

3 Construct an AVL tree from given data.


I/Ps : 50, 40, 35, 58, 48, 42, 60, 30, 33, 32

Insert 50

Insert 40

50

40

35

Insert 35

40

50
35

58

Insert 58

40

50
35

58
48

Insert 48

Powered by iBirat Technologies <http://www.ibirat.com> 59


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

40

35
50 Right to left
rotation
58
48

42
Insert 42

48
48
50
48 40
35
58
50 42
42 35
58
Step – I Step –ii

48
48
50
40 58
58 40 60
42
60
35 42 50
Perform R R 35
Insert 60
Insert 30
48

58
40
60
42 50
35

30

Powered by iBirat Technologies <http://www.ibirat.com> 60


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

2
48
2 58
40
60

2 42 50
35

-1
30

33

Insert 33

48
48
48 48

48 48
48

48

48

48

58
40
60
48 50
33

30 35
Step I Step II

Powered by iBirat Technologies <http://www.ibirat.com> 61


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

48

58
33

60
30 40 50

42
25 35

48
58
40
60
42 50
33

30 35

25

Insert 25

Huffman Tree:-
0

1
1 Internalnode
2
2

2
2 3 3 Externalnode

3 4
3 4

Fig:- extended binary tree

Powered by iBirat Technologies <http://www.ibirat.com> 62


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Total path length of internal nodes:-


PI = 0 + 1 + 2 + 1 + 1 + 2 + 3 = 9
Total path length of external nodes:
PE = 2 + 3 + 3 + 2 + 4 + 4 + 4 + 3 = 21
If external node has weight w, then weighted path length for external node is
P = W1P1 + W2 P2 + ……….WnPn

Algorithm:-
4 Let us take there are n weights W1, W2, ………., ………., Wn
5 Take two minimum weights & create a subtree, suppose W1 & W2 are first two min
weight then subtree will be

W1 W2

6 Now the remaining weight will be W1 + W2, W3, W4…….Wn


7 Create all sub tree at the last weight.

Q. Construct an extended binary tree by huff man method.


A B C d E F G
Weight 16 11 7 20 25 5 16
Step:1 Taking two nodes with minimum weight 7 & 5,
12

7
5

Step:2 taking two nodes with minimum weight 11 & 12


23

12

11

7
5

Now the elements are 16, 23, 20, 25, 16


Step:3 Taking two nodes with minimum weight 16 & 16

Powered by iBirat Technologies <http://www.ibirat.com> 63


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

32

16
16

Now,
The elements are 32, 23, 20, 25

Step:4
43

20
23
12

11 7
5

Now the elements are 32, 43, 25


Step:5
100

43
57
20
25
57 23
32
12
32 25

16 16 11
16 16 5 7

Total path length:-


PI = 0 + 1 + 2 + 2 + 3 + 4 = 12
PE = 2 + 3 + 3 + 2 + 4 + 4 + 3 = 21

B – Tree “Balanced Tree”


1 It is also known as balanced sort tree.
2 The height of the tree must be kept to a minimum.
3 There must be no empty sub trees. Above the leaves of the tree.
4 The leaves of the tree must all be the same level.
5 All nodes except the leaves must have at least some minimum no of children.

Powered by iBirat Technologies <http://www.ibirat.com> 64


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

B – Tree of order n can be defined as:-


6 Each node has at least n+2 & maximum ‘n’ non empty children.
7 All leaves nodes will be at the same level.
8 All the leaf nodes contain minimum n-1 keys.
9 Keys are arranged in a defined order with in the node. All keys in sub tree to
the left of the key are the procedure of the key and that on the right are
successors of the key.
10 When a new key is to be inserted in to a full node, then split the nodes with
the median value is inserted in the parent node. In case the parent node is
root, a new node is created.
100

35 65
130 180

10 20 40 50 70 80 90 110 120 140 160 190 240 260

15 Each node at same leaves.


16 All non- leaf nodes have no empty subtree.
17 Keys 1 less than no. of their children.
Q. Construc a B – tree of order 5 inserting the keys:-
10, 70, 60, 20, 110, 40, 80, 130, 100, 50, 190, 90, 180, 140, 280.
n
Sol :-
10
Insert 10

10 70
Insert 70

10 60 70
Insert 60

10 20 60 70
Insert 20

60

10 20 70 110
Insert 110

Powered by iBirat Technologies <http://www.ibirat.com> 65


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

60

10 20 40 70 110
Insert 40

80, 130, 100, 150, 90, 180, 240, 30, 120, 140, 160
60
Insert 80

10 20 30 70 80 110

60

10 20 40 70 80 110 130
Insert 130

60 110

10 20 40 70 80 110 130
Insert 100

60 100

10 20 40 50 70 80 100 130
Insert 50

60 100

10 20 40 50 70 80 100 130 190


Insert 190

60 100

10 20 40 50 70 80 90 100 130 190


Insert 90

Powered by iBirat Technologies <http://www.ibirat.com> 66


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

60 100

10 20 40 50 70 80 90 100 130 180 190


Insert 180

60 100 180

10 20 40 50 70 80 90 100 130 190 240


Insert 240

30 60 100 180

10 20 40 50 70 80 90 100 130 190 240


Insert 30

30 60 100 180

10 20 40 50 70 80 90 110 120 130 190 240


Insert 120

30 60 100 180

10 20 40 50 70 80 90 110 120 130 140 190 240


Insert 140

100

30 60 130 180

10 20 40 50 70 80 90 110 120 140 160 190 240


Insert 160

Deletion in B- tree:-
1. node is leaf node.
2. node is non leaf
-if node has more than minimum no. of keys than it can be easily deleted.
-if it has only minimum no. of keys, than first we see the no. of keys in adjacent leaf node. If
it has more than minimum no. of keys then first key of the of the adjacent node will go to

Powered by iBirat Technologies <http://www.ibirat.com> 67


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

the parent node & key in parent node will be combined together in one node.
-If now parent has also less than minimum no. of keys then the same thing will be repeated
until it will gate the node which has more than the minimum no. of keys.
Node is non leaf:-
-In this case key will be deleted & it’s predessor or successor key will condition it’s place.
-If both nodes of predessor or successor key have minimum no. of keys then the rates of
predessor & successor keys will be combine.
100

30 60 100

10 20 25 40 50 70 80 90 140 120 140 160 190 240 260

100

30 60 100

10 20 25 40 50 70 80 90 110 120 140 160 240 260


Delete 190
100

30 60 130 180

10 20 25 40 50 70 80 90 110 120 140 160


Delete 60
Delete 40
100

25 70 130 180

10 20 30 50 80 90 110 120 130 160 240 260

Powered by iBirat Technologies <http://www.ibirat.com> 68


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

25 70 100 180

10 20 30 50 80 90 110 120 130 160 240 260


Delete 140

Question:- Construct a B- tree of order 5 I/P the element when keys are 659, 767, 702, 157,
728, 102, 461, 899, 920, 44, 744, 264, 384, 344, 973, 905, 999
Perform delete operation fro 44, 344, 920

Chapter – 8
Game tree:- 659, 767, 702, 157, 728, 102, 461, 899, 920, 44, 744, 264, 344, 973, 905, 999
Given,
Maximum no. of key = n – 1 = 4 element
Minimum no. of element = n/2 = 2 element in each node.
Maximum no of children = 5
659
Insert 659
659 767
Insert 767
659 702 767
Insert 702
157 659 702 767
Insert 157
702

157 659 728 767


Insert 728
702

102 157 659


Insert 102 728 767

702

1 0 2 1 5 7 4 6 1 65 9 728 767
Insert 461
702

1 0 2 1 5 7 4 6 1 65 9 728 767 899


Insert 899

Powered by iBirat Technologies <http://www.ibirat.com> 69


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

702

1 0 2 1 5 7 4 6 1 65 9 728 767 899 920


Insert 920
702

1 0 2 1 5 7 4 6 1 65 9 728 767 899 920


Insert 44
Insert 744
Insert 264 & 384
Insert 344
Insert 973 & 905 & 999
delete 44
delete 344 direct

Sorting:-
Sorting is storage of data in sorted order it can be in ascending or descending order.
Type
Internal sort
External sort
In internal sorting data i.e. going to be sorted will be in many memory. In external
…….will be on auxiliary storage , tape floppy disk etc.
Sorting Technique:-
Insertion Sort:-
The insertion sort inserts each element in proper place if there are n- element in
array and we place each element of array at proper place in the previously sorted element
list.

Algorithm:-
Consider N elements in the array are
Pass 1 arr[0] is already sorted because of only one element.
Pass 2 arr[0] is inserted before or after arr[0]. So arr[0] & arr[i] are sorted.

Powered by iBirat Technologies <http://www.ibirat.com> 70


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Pass 3 arr[2] is inserted before arr[0], in between arr[0] & arr[1] or after arr[0] . so
arr[0] , arr[1] & arr [2] are sorted.
Pass 4 arr[3] is inserted in to it’s proper place in array arr[0], arr[1], arr[2], arr[3] &
are sorted.
…………………
……………………
Pass N arr[ N-1] is inserted in to it’s proper place in array arr[0], arr[1], ……. Arr[N-
1]. So arr[0], arr[N-1] are sorted.

Q. Trace algo. With the given data using insertion sort.


82 42 49 8 92 25 59 52
Pass1 82 42 49 8 92 25 59 52
Pass 2 82 42 49 8 92 25 59 52
Pass 3 42 82 49 8 92 25 59 52
Pass 4 42 49 82 8 92 25 59 52
Pass 5 8 42 49 82 92 25 59 52
Pass 6 8 42 49 82 92 25 59 52
Pass 7 8 25 42 49 82 92 59 52
Pass 8 8 25 42 49 59 82 92 52
Pass 9 8 25 42 49 52 59 82 92

Selection Sort:-
Selection sort is the selection of an element & keepingit in sorted order. Let us take
an array arr[0]……..arr[N-1]. First find the position of smallest element from arr[0] to arr [n-
1]. Then interchange the smallest element from arr[1] to arr[n-1], then interchanging the
smallest element with arr[1]. Similarly, the process will be for arr[0] to arr[n-1] & so on.

Algorithm:-
Pass 1:- search the smallest element for arr[0] ……..arr[N-1].
- Interchange arr[0] with smallest element
Result : arr[0] is sorted.
Pass 2:- search the smallest element from arr[1],……….arr[N-1]
- Interchange arr[1] with smallest element

Powered by iBirat Technologies <http://www.ibirat.com> 71


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Result: arr[0], arr[1] is sorted.


…………………
…………………
Pass N-1:-
- search the smallest element from arr[N-2] & arr[N-1]
- Interchange arr[N-1] with smallest element
Result: arr[0]…………. Arr[N-1] is sorted.

Q. Show all the passes using selecting sort.


75 35 42 13 87 27 64 57
Pass 1 75 35 42 13 87 27 64 57
Pass 2 13 35 42 75 87 27 64 57
Pass 3 13 27 42 75 87 35 64 57
Pass 4 13 27 35 75 87 42 64 57
Pass 5 13 27 35 42 87 75 64 57
Pass 6 13 27 35 42 57 75 64 87
Pass 7 13 27 35 42 57 64 75 87

Buibble sort:- (exchange sort)


In bubble sort each element is compared with I’t adjacent element. If the 1st element
is large than the second one then the position of the elements are interchanged otherwise
it is not changed.

Alg.
If N elements are given in memory then for sorting we do the following steps:-
Pass:-
1. first compare the 1st element and 2nd element of array. If 1st < 2nd then compare the 2nd
with 3rd.
2. if 2nd > 3rd.
Then interchange the value of 2nd & 3rd.
3. now compare the value of 3rd with 4th.
4. similarly compare until N-1th element is compared with nth element.

Powered by iBirat Technologies <http://www.ibirat.com> 72


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

5. Now, highest value element is reached at the Nth place.


6. Elements will be compared until N-1 elements.
Or
Repeat through step 1 to 5 for N-1 elements.

Q. Show all the passes using bubble sort.


13, 32, 20, 62, 68, 52, 38, 46
Pass 1. 13 32 20 62 68 52 38 46
nd rd
Pass II 2 >3 -interchange.
13 32 20 62 68 52 38 46
Pass III 32<62 - no change.
13 32 20 62 68 52 38 46
Pass IV 62<68 - no change.
13 32 20 62 68 52 38 46
Pass V 68< 52 - interchange.
13 32 20 62 52 68 38 46
Pass VI 68 <38 - interchange
13 32 20 62 68 38 68 46
Pass V II 68<46; interchange
13 32 20 62 52 38 46 68

Pass 1 (i) 13 20 32 62 52 38 46 68
13< 20 ; no change
(ii) 13 20 32 62 52 38 46 68
(iii) 13 20 32 62 52 38 46 68
(iv) 13 20 32 52 62 38 46 68
(v) 13 20 32 52 38 62 46 68
(vi) 13 20 32 52 38 46 62 68
(vii) 13 20 32 52 38 46 62 68

Pass:- 3
(i) 13 20 32 52 38 46 62 68 ;13<20 no change
(ii) 13 20 32 52 38 46 62 68 ;20<32 “

Powered by iBirat Technologies <http://www.ibirat.com> 73


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

(iii)13 20 32 52 38 46 62 68 ;32<52
(iv)13 20 32 38 52 46 62 68 ;52< 38 change
(v)13 20 32 52 38 46 62 68
Pass :- 4
O/P 13 20 32 38 46 52 62 68

Q. Quick sort (partition exchange sort)


Quick sort is base on divide and conquer algorithm . In thi9s we divide the original list in
to two sub list . we choose the item from list called key or pivot from which all the left side
of elements aer smaller & all the right side of elements are greater than that element. Thus
we can create two list, one list is an the left side of pivot and 2 nd list is an right side of pivot.
Similarly, we choose the pivot for dividing the sublist until there are two or more elements
in the sub list.

Algorithm:-
(i) take the first element of list as pivot.
(ii) Place pivot at ht proper place in list.
For placing pivot at it’s proper place it follows following steps
Compare the pivot element one by one from right to left for getting the element
which has value less than pivot element.
Interchange the element with element.
Now, comperision will start from the interchange element position from left to
right for getting the element which has higher value than pivot.
Repeat the same process until pivot is at it’s proper position.
(iii) Create two sublists left & right side of pivot.
(iv) Repeat the same process until all elements of first are at proper position in list.

Q. Show the same process until all elements quick with the following.
48 29 8 59 72 88 42 65 95 19 82 68
Soln:- Pass(i)
48 29 8 59 72 88 42 65 95 19 82 68
(ii) interchange
19 29 8 59 72 88 42 65 95 48 82 68

Powered by iBirat Technologies <http://www.ibirat.com> 74


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

(iii) large element interchange


19 29 8 48 72 88 42 65 95 59 82 68
(iv) interchange
19 29 8 42 72 88 48 65 95 59 82 68
(v) interchange
19 29 8 42 48 88 72 65 95 59 82 68
For sub list 1.
(i) 19 29 8 42 search small element
(ii) 8 29 19 42
Search large element
(iii) 8 19 29 42
Sublist sublist 22
Now, consquaring sublist 11 & sublist 12 with pivot (19) we get,
8, 19, 29, 42
For sublist 2
88 72 65 95 59 82 68
68 72 65 88 59 82 88
68 72 65 88 59 82 95
68 72 65 82 59 88 95
Sub list 21
For sub list 21.
Similarly, perform above proces

Merge Sort:-
IN merge sort we take a pair of conjugative array elements then merge them in
sorted array & take adjacent pair of array elements & so on. Until all elements of array are
in single list.
e.g. 5 8 89 30 92 64 4 21 56
pass1 5 8 89 30 92 64 4 21 56
pass2 5 8 30 89 64 92 4 21 56
pass3 5 8 30 89 4 21 64 92 56
4 5 8 21 30 56 64 89 92
Algorithm :- at last:-

Powered by iBirat Technologies <http://www.ibirat.com> 75


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Shell sort (Diminishing increment sort)


Shell sort is an improvement an insertion sort. In this case we take on itme at a
particular distance (increments) than we compare items which are far apart and then sort
them. After- words we decrease the increments & repeate this process again. At last we
take the increment one & sort them with insertion sort.

Procedure:-
1 Let us take an array from arr[0], arr[1]……… arr[N-1] & take the distance 5 (say) for
grouping together the items then in terms will grouped as:
First: arr[0], arr[5], arr[10],……….
Second: arr[1], arr[6], arr[11],………
Third: arr[1], arr[7], arr[12],……..
Fourth: arr[9], arr[8], arr[13]…….
We can see that we have to make the list equal to the increments & it will cover all
the items from arr[0]………arr[N-1].
2 First sort this list with insertion sort then decrease the increments & repeat this process
again.
3 At ht end, list is maintained with increment 1 & sort them with insertion sort.
Question:- Show all the passes using shell sort with following list:-
75 35 42 13 87 27 64 57
n
Sol :-
Consider increments 5
Pass1: 75 35 42 13 87 27 64 57

Pass 2 27 35 42 13 87 75 64 57

Pass 3 13 35 42 27 57 75 64 87

4 13 27 35 42 57 64 75 87
Explanation:-

Powered by iBirat Technologies <http://www.ibirat.com> 76


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Binary Tree sort:-


1. Create binary search tree.
2. Find in order traversal of binary tree.

Question:-
19 35 10 12 46 40 6 90 3 8
19
35
46
10
12 90

6 40

8
3
[do step by step]

In order traversal
3 6 8 10 12 19 35 40 46 90
Heap Sort:-
Heaps:-
A heap is a binary tree that satisfied the following propertiers:-
shape property
Order property.
By the shape property we mean that heap must be a complete binary tree where as
by order property we mean that for every node in the heap the value store in the heap
node is greater than or equal to the value to the value an each of its’ children. A heap that
satisfied this property is known as max heap.
However, If the order property is such that for every node. In the heap the value
stored in that node is less than or equal to the value in each of it’s children. That heap is
known as minimum heap.
e.g create the heap tree.
10 5 70 15 12 35 50

Powered by iBirat Technologies <http://www.ibirat.com> 77


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

10
70
5 50
35
12
15

- Here root no must be greater than children here 5< 15 so, we inter change it’s position.
10
70
5
50
35
12
15

- Now, in position 2, 5, & 6 the 70 is greater than 35 & 50. so we can’t interchange.
- On the other hand the.
70
50
15 10
35
12
5

Heap sort:-
The elements of the heap tree are represented by an array . The root is the larget
element of heap tree. As it is maintained in the array. The largest element of heap tree. As it
is maintained in the array. The largest value should be the last element of array. For heap
sorting root is deleted till there is only one element in the tree.
Steps:-
1. Replace the4 root with the last node of heap tree.
2. Keep the last node at proper position.
3. Repeat step 1 & 2 until there are only one root node in the tree.

Powered by iBirat Technologies <http://www.ibirat.com> 78


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]
a r r [0 ]
72
a rr [ 2]
65
a r r [6 ]
6 4 a r r [1 ] 54
46 a rr [ 5]
ar r [9 ] 32
56 ar r [4 ]

29 4 8 ar r [8 ]
a r r [7 ]

0 1 2 3 4 5 6 7 8
arr 72 64 65 56 32 46 54 29 48
Step:-1 Root node is delete and this root node is replaced by last node and the previous
value of root node is placed in proper place in array.
48
65

64 54
46
12
56

29 48 64 65 56 3 2 5 4 2 9 72

Here, root node is less than 65. so we interchange the position to make heap tree.
65
64 54
56 32 46 48
29
Again , 48< 54
65
64 54
56 32 46 48
29
Now, which is in Heap tree form.
6 5 6 4 5 4 5 6 3 2 4 6 4 8 29 72

Again , delete root node & put 29 in root node.


2 9 6 4 5 4 5 6 3 2 3 2 4 6 48 6 5 7 2

Powered by iBirat Technologies <http://www.ibirat.com> 79


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

2 9 6 4 5 4 5 6 3 2 3 2 4 6 48 6 5 7 2

6 5 6 4 5 4 5 6 3 2 4 6 4 8 29 72

Powered by iBirat Technologies <http://www.ibirat.com> 80


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Radix sort:-
In radix sort, we sort the item in terms of it’s digits. If we have list of nos. then there
will be 10 parts from 0 to 9 because radix is 10.
Algo
1. consider the list n digit of nos, then there will be 10 parts from 0 to 9.
2. in the first pass take the nos in parts on the basis of unit digits.
3. In the second pass the base will be ten digit.
4. Repeat similarly for n passes for n digits.

Show all the passes using radix sort.


233 124 209 345 498 567 328 163
Pass 1
Numbers [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
233 233
124 124
209 209
345 345
498 498
567 567
328 328
163 163

Pass 2
233 163 124 345 567 498 328 209
Number [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
233 233
163 1 163
124 124
345 345
567 567
498 498
328 328
209 209

Powered by iBirat Technologies <http://www.ibirat.com> 81


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

209, 124, 328, 233, 345, 163, 567, 498.

Taking hundred position:-


Number 0 1 2 3 4 5 6 7 8 9
209 209
124 124
328 328
233 233
345 345
163 163
567 567
498 498

Hence, required sequence is


124 163 209 233 328 345 498 567

Chapter – 9
Searching
Definition:-
Searching is used to find the location whether element is available or not. There are
various kinds of searching techniques.
1. sequential search:-
simplest technique for searching on unordered table for particular record is to scan
each entry in sequential manner until the desired record is found.
2. If search is successful then it will return the location of element otherwise it will
return failene notification.

Consider, sequential search in array.


Arr [0] [1] [2] [3] [4] [5] [6]
10 20 30 40 50
Algorithm:-
Put a unique value at the end of array. Then.

Powered by iBirat Technologies <http://www.ibirat.com> 82


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

(i) index =0
(ii) scan each element of array one by one.
(iii) (a) If match occurs then return the index value.
(b) otherwise index = index +1
(iv) Repeat the same process until unique value comes in scanning.
(v) Return the failure notification.
Consider sequential search in linked list.
Algorithm:-
1) Take a pointer of node type and initialize it with sort
Ptr = start
2) Scan each node of the linked list by traversing the list with the help of ptr.
Ptr = ptr link;
3) If match occur then return.
4) Repeat the same process until null comes in scanmning.
5) Return the failure notification.

Performance analysis:-
Number of key comparison taken to find a particular record
Average case : (n+1)/2
Warpe case: n+1
Best case:- if desired record is present in the 1st positon of search table i.e. only one
comparison is made.

Binary search:-
The sequential search situation will be in worse case i.e. if the element is at the end
of the list. For eliminating this problem one efficient searching techinique called binary
search is used in this case.
1. the enteries are stored in sorted array.
2. The element to be searched is compared with middle element of the array.
a. If it is less than the middle element then we search. It in the left portion of the
array.
b. If it is greater than the middle element then search will be in the right portion of
the array.

Powered by iBirat Technologies <http://www.ibirat.com> 83


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

3. The process will be in iteration till the element is searched or middle element has no
left or right portion to search.

Algorithm:-
Binary search (K.N, x)
entries in ascending order.
(i) [initialize]
Start 0, end N
(ii) Perform search
Repeat through step (iv) while low high
(iii) [obtain index of mid point of interval]
Middle [ (start + end)/2]
(iv) Compare
If X<K (middle)
Then end middle -1
Else
If X>K(middle);
Then start middle +1
Else
Write (“Successful search”)
Return (middle)
(v) [unsuccessful search]
Return (0)
Question:- Tress a Binary search algorithm I/P data:-
75, 151, 203, 275, 318, 489, 524, 591, 647, 727
Search Pop x = 275, 727, 725.
n
Sol :- [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
75 151 203 275 318 489 524 591 647 727

Iteration:1
0+ 9
=4
Start = 0 end = 9 middle = 2
Since middle element [4] = 318

Powered by iBirat Technologies <http://www.ibirat.com> 84


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Since, the middle element is greater than search element, so we assign,


Iteration:-2
0+3
=1
Start = 0 end = 3 middle = 2
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
75 151 203 275 318 489 524 591 647 727
151 < 275
Now,
Start = middle + 1 = 2 end = 3
Iteration:- 3
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
75 151 203 275 318 489 524 591 647 725
203 < 275 end = 3
Iteration :- 4
3+3
=3
Middle = 2
275 = 275
Middle [3] = 275

For 725
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
75 151 203 275 318 469 524 591 647 727
Iteration:-1
0+9
=4
Start = 0 end = 9 middle = 2
725> 318
Iteration:-2
5+9
=7
Start = 5 end = 9 middle = 2
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
75 151 203 275 318 489 524 591 647 727
725 < 591

Powered by iBirat Technologies <http://www.ibirat.com> 85


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Iteration:-3
8+9
=8
Start = 8 end = 9 middle = 2
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
75 151 203 275 318 489 524 591 647 727
725 < 647
Iteration:- 4
9+9
=9
Start = 9 end = 9 middle = 2
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
75 151 203 275 318 489 524 591 647 727
725 < 727
Binary search tree:- (BST)
Algorithm:-
1. [initialize]
Read (no)
Root node content = 0
Right subtree = NULL
Left sub tree = NULL
2. while there is data
Do
Begin
Read(no)
3. compare no. with the content of root.
4. Repeat
If match then declare duplicates
Else
If no < root, then
Root = left sub tree root
Else
Root = right sub tree root.
Until
Duplicate found or (root = = NULL)

Powered by iBirat Technologies <http://www.ibirat.com> 86


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

If(root = = NULL) then place it as root.

Application of BST:-
(i) sorting a list
construct a BST &
Traverse in in order
(ii) For conversion prefix, infix & posfix expression.
construct a BST &
traverse in preorder, post order, inorder

Alorithm to build a binary search tree (BST) from post fix expression
Read symbol at a time.
If symbol is a operand.
* create one node tree push pointer to stack.
if symbol is operator
1 pop pointer to two trees T! and T2 & form a new tree whose root is children
point to T1 & T2 respectively.
2 Pointer to this new tree is then pushed to stack.
Ab+ cde + **
3.

1.

+ c +

a b a b d e
+

Powered by iBirat Technologies <http://www.ibirat.com> 87


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

2.
4.

+ + + *
c
+
a b c

a b d +
e d e *

5.

* +

a c +
b

d e

Inorder:-
Preorder:-
Post order:-

“Hashing”
Sequential search, binary search and all the search trees are totally dependent on
no. of element and may key comparisons are involved. Now, our need is to search the
element in constant time and loss key comparisons should be involved.
Suppose all the elements are in array of size ‘N’. Let us take all the keys are unique
and in the rage ‘o’ to N-1. Now we are sorting the record in array based on key, where array
index and keys are same. Then we can access the record in constant time and no key
comparisons are involved.

Consider 5 records where keys are :-


9, 4, 6, 7, 2

The keys can be stored in array up


Arr [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
2 4 6 7 9
Here, we can see the record which has key value can be directly accessed through array

Powered by iBirat Technologies <http://www.ibirat.com> 88


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

index.
In hashing key is converted into array index and records are kept in array. In the
same way for searching the record, key are converted into array index and get the records
from array.

For storing records:-


Key

Generate array index


Key

Stored the record on that array index.


For accessing record:-
Key

Generate array index


Key

Get the records from the array index

The array which supports hashing for storing records or searching records is called
hash table. Each key is mapped on a particular array index through hash function. If each
key is mapped on a unique hash table then this situation is ideal but there may be possibility
that hash function generating some hash table address for different keys & this situation is
called collision. For missing collision we have to perform:

(a) Choose a good hash table which perform minimum collision.


(b) Resolving the collision.

Technique for choosing hash function.

Trunction method:-
In this method a part of hey is considered as address, it can be some rightmost digit
or leftmost digit.

Q. apply the truncation method to get the hash index of table size of 100 for following keys.

82394561, 87139465, 83567271, 85943228


Soln:

Table size = 100


Then,
Take 2 rightmost digits for getting the hash table address.

Powered by iBirat Technologies <http://www.ibirat.com> 89


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Key value address


82394561 61
87139465 65
83567271 71
85943228 28
Example. h(key) = a
h(823994561) = 61

Mid square method:-


In this method we square the key , after getting number we take some middle of
that number as an address, suppose keys are 4 digits and maximum address = 100.
Key value square address
1456 02119936 19 h(1456) = 19
1892 03579664 79 h(1892) = 79

3. folding method:-
In this method we break the key in to pieces & add them and get the address.
Suppose 10 digit key 1234567890 may be reduced to key 50, 000 storage location by
carrying out the steps.
1234567890
Steps:-
1. 1234567890
2. 34567
+12890
47457
3. number > 50, 000?
4. if no; number = address
5. if yes, subtract 50,000 with the no until no<50,000.

H(1234567890) = 47457

Modulus method:-
Modular method is best way for getting address from key take the key, do they
modulus operation & get the remainder as address for hash table in order to minimize the
collision table size should a prime number consider keys.

82394561, 87139465, 83567271, 89943228


& Table size = 97
Then, address are
82394561 % 97 = 45
87139465 % 97= 0

Powered by iBirat Technologies <http://www.ibirat.com> 90


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

83567271% 97=25
89943228% 97= 64

82394561 = 82 = 3945 + 61= 4088


87139465 = 87 + 1394 + 65=
83567271= 83 + 5672 +71=
89943228 = 89 + 9432 + 28=
Applying modulus method we get,
4088 % 97 = 14.

5. Hash function for floating point numbers:-


The operations can be performed as
i. Check the fractional part of key.
ii. Multiply the fractional part with the size of the hash value.
iii. Take the integer part of the multiplication result as a hash address of key.

e.g. Question:- Consider the key as floating point number as


123.4321, 19.469, 2.0289, 8.9956
Hash size = 97
Soln:-
0.4321 x 97 = 41. 9139
0.463 x 97 = 44.911
0.0289 x 97 = 2.8906
0.9956 x 97 = 96.5732
Here, hash address will be integer part of these numbers
i.e. H(123.4321) = 41
H(19.463) = 4
H(2.0289) = 2
H(8.9956) = 96

6. Hash function for string:-


iv. In this case we add the ASCII value of each character and then apply modulus
operation on this value.
e.g consider the table size = 97
PUSET
PUSET = P + U + S + E + T
= 112+ 117 + 115 + 101 + 116
= 561
Now,
Applying modulus operation, we get
H(PUSET) = 561% 97
= 76
Hence, puset lies on the 76th address of hash table.

Powered by iBirat Technologies <http://www.ibirat.com> 91


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

v.In second method ASCILL value of each character is multiplied by 127 i.e. maximum
value of ASCII character and then perform modulus operation.
e.g.
table size = 997
PUSET =
PUSET = P + U + S + E + T
= (112 + 117+ 115 + 101 + 116) x 127
= 71247
Now, applying modulus operation, we get
H(PUSET) = 71247 % 997
= 460
Q. 1. Apply the folding and modulus method to get the hash index of table size 11 for
following keys.
8925, 23197, 37565, 48693, 46453
Q. 2. :- Get the hash index in the table size 29 for the following floating point number.
56.9281, 145.0092, 28.45, 28.45 , 89.3967, 2.877
Q 3. :- Get the hash index in the table size 19 for the following keys.
PUSET, eastern, khoppa, acme, novel
Q 4. :- apply the truncation method to get the hash index of the table size 997 for following
keys.
699934, 674352, 632433, 678433, 678668, 629871, 653420
Q 5:- apply folding method to get the hash index of table size 79 for the following keys.
56497, 79256, 27143, 49239, 18942, 77722
Q 6:- apply the mid- square method to get the index of table size 97 for the following keys.
1123, 1234 1012, 1034, 1103, 1005

# collision Resolution technique:-


1. open chaining : separate chaining
2. closed chaining.
i. Linear probing
ii.Quadratic probing
iii. Double hashing
iv. Rehashing.
3. Open chaining (separate chaining):-
This method maintains the chain of elements which have same hash address. We
can take hash table as an array of pointers. In this method each pointer will point to
one linked list and the elements which have same hash address will be maintained in
the linked list basically it involves two operations.
(i) creation of god hash function for getting hash key value in the hash table.

Powered by iBirat Technologies <http://www.ibirat.com> 92


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

(ii) Maintain the elements in the linked list which is pointed by the pointer
available in hash table.
\0
e.g. 0

I/P keys:- 13, 15, 6, 24, 23 & 20 1 \0 15


Table size :- 7 2
Hash function h(x) = x %7 \0 23

h(13) = 13%7 = 6 3
\0 24
h(15) = 15%7 = 1 4
\0
h(6) = 6%7 = 6
h(24) = 24%7 = 3 5
\0
h(23) = 23 % 7 = 2
h(20) = 20%7= 6
6
2. Closed chaining (open addressing) \0 13 6
(iii) Linear probing:-
20
This hashing technique finds the hash key value
through hash function and maps the key on the particular position in hash in hash,
table. In case if key has same hash address then it will find the next empty position
in the hash table we take the hash table as arcular array. If table size in n then after
n-1 position it will search form zeroth position in the array.
e.g. consider table size 11 & elements are
29, 18, 23, 10, 36, 26, 46, 43
Soln:- 0
1
H(29) = 29%11 = 7 2
H(18) = 18 %11= 7 3
H(23) = 23%11 = 1 4
H(10) = 10%11= 10 5
H(36) = 36%11= 3 6
H(25) = 25%11= 3 7
H(46) = 46%11= 2 8
9
H(43) = 43%11= 10
10
Disadvantage of linear probing:-
dustering problem.
searching is slow. 0 10
1
Quadratic probing:-
In case of collision 2 46
2
Rehash functions : (Hash value + 1 ) % size 3 54
(Hash value + 22) % size & so on. 4
This technique decrease the problem of dustering but can’t
search all the locations, if hash table is prime then it will search 5 at least
half of the locations of hash table. 6
e. g. 7 29
8 18
Powered by iBirat Technologies <http://www.ibirat.com> 93
Resource downloaded from http://pu.ibirat.com
9
10 43
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

table size = 11
given elements = 29, 18, 43, 10, 46, 54
H(29) = 29% 11= 7
H(18) = 18%11 = 7
(hash value + 12) %11
(7 + 1 ) % 11 = 8
H(43) = 43%11= 10
H(10) = 10 % 11 = 10
(Hash value + 12) %11
H(46) = 46%11 = 2
H(54) = 54%11 = 10
(10 + 12) %11 = 0
(10 + 22) % 11= 3

Double hashing :-
This technique requires hashing second time in case of collision. Suppose h is a hash
key then in case of collision we will again do the hashing of this hash key.
i.e. Hash( h) = h’
now,
we will search the hash key location as h, h+h’, h+2h’ & h+3h’ & so on.
Consider, the table size = 13 then two hash functions are
H = key % 13
& h’ = 11(key % 11)
At the time of collision, hash address for next probability is (h+h’) % 13
((key % 13) + (11 – (key %11) ))) % 13
Or, h+ 2h’
Or, (key % 13) + 2(1) – key % 11)) 0
Question:- consider elements 8, 55, 48, 68 table size = 13 1
h = key % 13 2
h’ = 11 – (key % 11) 3 55
now, applying modulus operation,
4
h(8) = 8%13= 8
h(55) = 55%13= 3 5
h(48) = 48%13 = 9 6
h(68) = 68 % 13= 3 7
hence, collision occurs at table location 3. 8 8
so, applying double hashing, we get 9 48
(key % 13) + (11- key %11) ) % 13
10
(3 + 11 – 2) % 13 = 12 % 13 = 12
11
Advantages:- 12 68
we do operation faster.

Powered by iBirat Technologies <http://www.ibirat.com> 94


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Draw backs:-
Requires two times calculation of hash function, which creates if complex &
searching will be slower than linear & quadratic probing.

Rehasing:-
There are chances of insertion failure when hash table is full, so the solution for this
particular case is to create a new hash table with the double size of previous hash table.
Here, we will use new hash function and we will insert all the elements of the pervious hash
table. So, we will scan the elements of previous hash table one by open & calculate the
hash key with new hash function & insert them into new hash table.
0 10
Consider the table size 11 & elements are 1
7, 18, 43, 10, 36, 25………..
2
Soln:- Size = 11
Applying linear probing we get 3 36
h(7) = 7%11= 7 4 25
h( 18) = 18%11= 7 5
h(43) = 43%11= 10 6
h(10) = 10%11= 10 7 7
h(36) = 36%11= 3
8 18
h(25) = 25%11= 3 0
9
now, if we want to insert six more element then size will not be 12
25
sufficient . In order to fit all the elements or key with in a table 10 43 we 3
take new table of size more than double with prime number. Thus total size is 23. 4

Applying linear probing, we get, 5


6
h(7) = 7%23= 7 7
h(18) = 18%23 = 18 8

h(43) = 43%23 = 20 9
10 10
h(10) = 10%23 = 10 11
h(36) = 36%23= 13 12

h(25) = 25%23 = 2 13 36
14
.. …. 15
.. .. 16

.. .. 17
18 18
19
20 43

Disadvantage:- 21
22
This method is more expression.
CHAPTER :- 10
Graph:-
A graph B is a collection of two sets V & E where V is the collection of vertices . V 0,
V1……….Vn-1 also called nodes & E is the collection of edges e1, e2, ……….en .where an edges
is an arc which connects two nodes. This can be represented as

Powered by iBirat Technologies <http://www.ibirat.com> 95


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

G = (V,E)
V(G) = (V0, V1……….Vn-1 ) or set of vertices.
E(G) = (e1, e2, ……….en) or set of edges.

Types:-
1. undirected
2. directed.

1. Undirected:-
A graph which has unordered pair of vertices is called undirected graph. Suppose
there is an edge between V0 & V1 then it can be represented as
(V0, V1) or (V1, V0).
Vo 1 2
V1
V(G) = { 1, 2, 3, 4}
E(G) = {(1, 2), (1, 4), (1, 3), (2, 3), (2, 4), (3, 4)}
4
3

2. Directed:-
A directed graph or digraph is a graph which has ordered pair of vertices (V 1, V2)
where V1 is the tail & V2 is the head of the edge.
2
Vo V1 1

( V 1, V 2) V(G) = { 1, 2, 3, 4}
E(G) = {(1, 2), (1, 4), (1, 3), (2, 3), (2, 4), (3, 4)}
4
3
Weighted graph:-
A graph is said to be weighted if it’s edges have been assigned with some non
negative as weight.

Adjacent nodes:-
A node u is adjacent to another node or is a neighbor of another 3
2
1
node V if there is an edge from u to node V. In undirected graph if(V o, V1) is
an edge then Vo is adjacent to V1 & V1 is adjacent to Vo. In a digraph if (Vo, V1) 6
is an edge then Vo is adjacent to V1 & V1 is adjacent from Vo.
4
3

Path:-
A path from node u0 to node un is a sequence of nodes u0, u1 , u2……… un-1 , un such
that u0 is adjacent to u1, u1 is adjacent to u2 …………….. un-1. is adjacent of un

Length of Path:-
Length of a path is the total number of edges included in the path.

Powered by iBirat Technologies <http://www.ibirat.com> 96


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Closed path:-
A path is said to be closed if first & last node of the path are same.
1 2

3 4
1 2
Simple Path:-
It is a path in which all the nodes are distinct with an exception that
the first & the last nodes of the path can be same.
3
4
Cycle:-
Cycle is a simple path in which first & last nodes are the same.
A

A
C B

A
Cyclic graph:-
A graph that has no cycles is called Acyclic graph.
C B

Degree:-
IN an undirected graph the number of edges connected to a node is called the
degree of that node or degree of a node is the no. of edges incident on it.

A B

C D

Indegree:-
The indegree of a node is the number of edges coming to that
node. A B

Here, in degree of nodes:-


A=0 C D E
B=2
C=2
D=6
F G
Powered by iBirat Technologies <http://www.ibirat.com> 97
Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

E=1
F=0
G=1
Outdegree:-
The out degree of a node is the number of edges going outside form the node.
Out degree of A=3
B=1
C=1
D=0
E=2
F=3
G=2

Isolated node:-
If a node as no edges connected with any other node then it’s degree will be zero &
is called as isolated node
A C

B D
C is isolated node.

Successor or predessor:-
In digraph if a node Vo is adjacent to node V1 then Vo is the predessor of V1 & V1 is
the successor of Vo,
Vo V1
Connected graph:-
An undirected graph is connected if there is a path from any node of a graph to any
other node.
B A B
A

C C
D D

Here, G1 is connected Graph while G2 is unconnected graph.


A
Strongly Connected:-
A digraph is strongly connected if there is a directed path from any
node of graph to any other node.
C B

Weakly connected:-
A digraph is called weakly connected for any pair of nodes u & v, there is A a

Powered by iBirat Technologies <http://www.ibirat.com> 98


Resource downloaded from http://pu.ibirat.com
C B
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

path form u to v r a path from v to u but not both.

Maximum, edges in graph:-


n(n − 1)
In undirected graph maximum edge = 2 & in digraph.
Maximum edges = n(n -1)
Where, n is the total no. of nodes in the graph. A
n(n-1)/2
= 3(8 -1)/2
=3 C B

n(n -1) A
3(3 -1) = 6

C B

Representation of Graph
Two ways:-
Sequential representation (adjacency matrix)
linked list representation (adjacency list)

Adjancy matrix:-
Adjancy matrix is the matrix which keeps information of adjacent nodes i.e. keeps
the information weather node is adjacent to any other node or not. Suppose there are four
nodes in a graph then row one reprew3ents the node 1, row 2 represents the node 2 & so
on . similarly, column 1 represents node 1 & column 2 represents node 2 & so on. The entry
of the matrix will be.
Arr[i][j] = 1 if there is an edge from node I to node j
= 0 if there is no edge from node I to node j.

B A B C D outdegree
A
A 0 1 0 1 2
B 1 0 1 1 3
C 0 0 0 1 1
C D 1 0 1 0 2
D
indegree 2 1 2 3

again,
For undirected graph:-

Powered by iBirat Technologies <http://www.ibirat.com> 99


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

A B
A B C D
A 0 1 1 1
B 1 0 1 1
D
C C 1 1 0 1
D 1 1 1 0
It has no in degree & out degree because it has no direction of node.

Representation of weighted graph in matrix form:-


If graph has some weight on it’s edge then,
Arr[i][j] = weight on edge (if there is an edge from I to node j
= 0 (otherwise)
3
B
A
2 Weighted adjacency matrix
A B C D` out degree
9 8 7
A 0 2 0 8 10
C
B 3 0 4 7
D 6 C 0 0 0 5
5 D 9 0 6 0
Indegree =

Warshall Algorithm:-
Used for finding path matrix of a graph

Algorithm:-
1. Initialize
P A
2. [perform a pass]
Repeat through step 4 fro K = 1, 2, ……….n
3. process row]
Repeat step 4 for I = 1, 2, ………..n
4. process columns]
Repeat for j= 1, 2, ……….n
Pij U (Pik Pkj)
5. [finish]
Return
Q:- From the given graph find out the path matrix by warshal algorithm.

A B C D`
A 0 1 0 1
P0 = B 1 0 1 1 A B
C 1 1 0 1
D 1 1 1 0

C
Powered by iBirat Technologies <http://www.ibirat.com> D 100
Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Pij (Pik Pkj)


For k = 1
Pij (Pi1 P1j)

A B C D
A 1 0 1 0
P1 = B 1 1 1 1
C 0 0 0 1
D 1 1 1 1

Similarly taking k = 2 Pij = Pij (Pik Pkj)


Pij = Pij (Pi2 P2j)

A B C D`
A 1 1 1 1
P2 = B 1 1 1 1
C 0 0 0 1
D 1 1 1 1
Now taking k = 3,

A B C D`
A 1 1 1 1
P3 = B 1 1 1 1
C 0 0 0 1
D 1 1 1 1

Again taking k = 4
A B C D`
A 1 1 1 1
P4 = B 1 1 1 1
C 1 1 1 1
D 1 1 1 1

Here, P0 is the adjency matrix & Pu is the path matrix of the graph.

Q:- Modified warshal’s algorithm:-


Warshall’s algoritham give the path matrix of graph. By modifying this algorithm, we
will find out the shortest path matrix Q. Qij represent the length of shortest path from Vi to
Vj. Here, we consider the matrices q0, q1, q2, ………. qn.
Thus, length of shortest path from Vi to Vj using nodes Vj,V2, ….Vn
Qk[i][j] =
[i] there is no path from Vj to Vj using nodes V1, V2……………. Vn

Powered by iBirat Technologies <http://www.ibirat.com> 101


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Procedures:-
In this algorithm length of 1st path will be Qk-1 [i][j]
length of 2nd path will be Qk-1 [i][j] + Qk-1 [i][j].
Now, select the smaller one from these two path length so value of
Qk [i][j] = Minimum [Qk-1 [i][j], Qk-1 [i][j] + Qk-1 [i][j] ]

Algorithm:-
Q A
- adjacency matrix with 0 replaced by
[Perform a pass]
- Repeat through step 4 for k = 1,2, ………..0.
[process rows]
- Repeat step 4 fro j = 1,2, …………n
[process column]
- Repeat for j = 1,2, ……….n
Qk [i][j] Min [Qk-1 [i][j], Qk-1 [i][j] + Qk-1 [i][j] ]
[finish]
- Return

Case :-1
Qk [i][j] = & Qk-1 [i][j] + Qk-1 [i][j] =
Then, Qk [i][j] =min ( , ) =

Case :-2
Qk [i][j] = & Qk-1 [i][j] + Qk-1 [i][j] = b
Then, Qk [i][j] =min ( ,b ) = b
Case :-3
Qk [i][j] = a & Qk-1 [i][j] + Qk-1 [i][j] =
Then, Qk [i][j] =min (a, ) = a

Case :-4
Qk [i][j] = a & Qk-1 [i][j] + Qk-1 [i][j] = b
Then, Qk [i][j] =min (a,b)

Traversal in graph:-
There are two efficient techniques for traversing the graph.
1) depth first search (DFS)
2) Breadth first search (BFS)

Difference between traversal in graph & traversal in tree or us


1. There is no 1st node or root node in graph . Hence the traversal can start from any

Powered by iBirat Technologies <http://www.ibirat.com> 102


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

node
2. In tree or list when we start traversing from the 1 st node, all the nodes are traversed
which are reachable from the starting node. If we want to traverse al the reachable
nodes we again have to select another starting node for traversing the remaining
nodes.
3. In tree or list while traversing we never encounter a node more then once but while
traversing graph,. There may be a possibility that we reach a node more than once.
4. In tree traversal, there is only one sequence in which nodes are visited but in graph
for the same technique of traversal there can be different sequences in which node
can be visited.

Breadth first search:-


This technique uses queue for traversing all the nodes of the graph. In this we take
any node as a starting node than we take all the nodes adjacent ot that starting node.
Similar approach we take for al other adjacent nodes which are adjacent ot the starting
node & so on. We maintain the start up of the visited node in one array so that no node
can be traversed again.

Algorithm:-
1. [initialize]
Mark all vertex unvisited
2. begin with any node.
Insert it into queue (initially queue empty)
3. Remove node from queue.
23 append it to traversal list.
24 Mark it visited.

4. insert al the unvisited or node snot an queue in to the queue.


5. Repeat step 3 to 5 until queue is empty.
6. [Finish]
Return.

Figure:-

Thus the traversal list is


1 2 8 3 4 5 6 7

Depth first Search:-


This technique uses stack for traversing all the nodes of the graph in this we take
one as starting node then go to the path which is from starting node & visit all the nodes
which are in that path. When we reach at the last node then we traverse another path
starting from that node. If there is no path in the graph from the last node then it returns

Powered by iBirat Technologies <http://www.ibirat.com> 103


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

to the previous node in the path & traverse another & so on.

Algorithm:-
*
1 2 8 3
*
2 1 4 5
* *
3 1 6 7
* *
4 2 8
5 2 8
*
6 3 8
* *
7 3 8
* * * *
8 4 5 1 6 7

Traversal:-
1 2 8 3 4 5 6 7

Question :-
1 2 3

4 5 6

7 8 9
Breadth first search:-
1

2 4 5
4 5 3
5 3 7 6
6 7 6 8
7 6 8
6 8
8
9

Thus traversal list is


1 2 4 5 3 7 6 8 9
Depth first search:-

Powered by iBirat Technologies <http://www.ibirat.com> 104


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

*
1 4 5 2
*
2 5 3
3 1 6
*
4 7
* *
5 8 6
6
*
7 5 8
*
8 9
*
9
Traversal is
1 4 7 5 8 9 6 2 3

Shortest path algorithm:-


used to find the shortest path form one node to another node.
A single source vertex & seek shortest path to all other vertices.
shortest path is that path in which the sum of weight of included edges is minimum.
2 C
B
2 1
2
A 3
4 2
D E H
1
3 3
7
F
G
5

From A
Shortest path to B=2
C=2+2=4
D = ( 2 + 2) or (1 + 3) = 4
E=4
F=1
G=6
H=5

Powered by iBirat Technologies <http://www.ibirat.com> 105


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

2
B V
2
2
1
A D
1 H
E
3
F
5 G

Dis Kstra algorithm:-


In this technique each node is labeled with distance (dist) predecessor & status,
distance of node represents, the shortest distance of that node from the source node &
predecessor of a node represents the node which precedes the given node in shortest path
form source. Status of a node can be permanent or temporary.
shaded circle represent permanent nodes which indicates that it has been included in the
shortest path.
Temporary nodes can be relabeled if required but once node is made permanent, it
can’t be rebelled.

Procedure:-
Initially make source node permanent and make it the current working node . al
other nodes are node temporary.
Examine all the temporary neighbors of the current working nodes & after checking
the condition for minimum weight reliable the require node.
From all the temporary nodes find out the node which ahs minimum value of
distance, make the node permanent & now this is the current working node.
Repeat step 2 & 3 until destination node is made permanent.

5 V2
5 V1 16
4
7
2
V3 V4 3 V5 V6
5
6 3
3 4 2
V7
5 V8

Let , V1 = source node


Node dist pred status
V1 0 0 permanent
V2 0 temp
V3 0 temp
V4 0 temp

Powered by iBirat Technologies <http://www.ibirat.com> 106


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

V5 0 temp
V6 0 temp
V7 0 temp
V8 0 temp

Check adjacent node of V3


V4 Dis > V3 dis + distance (V3,V4) 7<2+ 4 relable.
V7 Dis > V3sis + sistance (V3, V7) >2+3 relable

Node dist pred status


V1 0 0 permanent
V2 0 temp
V3 0 temp
V4 0 temp
V5 0 temp
V6] 0 temp
V7 0 temp
V8 0 temp
Check adjacent node of V7
V4 Dis > V37 dis + distance (V7,V4) 7<2+ 4 relable.
V5 Dis > V7 sis + sistance (V7, V5) >2+3 relable V5

Node dist pred status


V1 0 0 permanent
V2 8 V1 temp
V3 2 V1 permanent
V4 6 V3 permanent
V5 9 V7 temp
V6] 0 temp
V7 5 V3 permanent
V8 0 temp

Check adjacent node of V4


V5 Dis > V4 dis + distance (V4,V5) 9<6+9 leave.

Node dist pred status


V1 0 0 permanent
V2 0 V1 permanent
V3 2 V1 permanent
V4 6 V3 permanent
V5 9 V7 temp
V6] 0 temp

Powered by iBirat Technologies <http://www.ibirat.com> 107


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

V7 5 V3 permanent
V8 0 temp

Check adjacent node of V2


V6 Dis > V2 dis + distance (V2,V6) >8 + 16 relable.
Node dist pred status
V1 0 0 permanent
V2 8 V1 permanent
V3 2 V1 permanent
V4 6 V3 permanent
V5 9 V7 permanent
V6] 24 0 temp
V7 55 V3 permanent
V8 0 temp

Check adjacent node of V5


V6 Dis > V5 dis + distance (V5,V8) >9 + 8
V6 Dis > V5 dis + distance (V6, V5) 24> 9+5

Node dist pred status


V1 0 0 permanent
V2 8 V1 permanent
V3 2 V1 permanent
V4 6 V3 permanent
V5 9 V7 permanent
V6 14 V5 permanent
V7 5 V3 permanent
V8 17 0 temp

Here, V6 is smallest & make it permanent since. V6 is the destination node make it
permanent & stop.
Now, start from destination node V6 & keep on seeing it’s perdecessors until we get
source node as predecessor.

Predecessor of V6 is V5
“ : “ V5 is V7
“ : “ V7 is V3
“ : “ V3 is V1
V1 V3 V7 V5 V6

Powered by iBirat Technologies <http://www.ibirat.com> 108


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Spanning tree:-
A spanning tree of a connected graph G contains all the nodes and has the edges
which connects all the nodes so that number of edges will be one less than the no. of nodes.
A B A B

C D C D
Fig a Fig a

A B A B A B

C D C D C D
Fig b Fig c
Fig d

Here, A B C D is a spanning tree & D is the minimum spacing tree.

Node:- 1 2 3 4 5 6 7 8 9
Father:- 0 0 0 0 1 0 0 0 0

Step :2 = selected is 4 -5 wet = 3.


n1 = 4 root n1 = 4 n2 = 5 root n2 = 1
Roots are different, so edge is inserted.
Father [1] = 4
Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 0 0 1 0 0 0 0

Step:- 4 edge selected is 3 – 6 wt = 5


n1 = 3 root – n1 = 3 n2= 6 root – n2= 6
father [6] = 3
roots are different so edge is inserted.
Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 0 0 1 3 0 0 0

Step: 5 edge selected is 5-6 wt = 6


n1 = 5 root – n1 = 4 n2= 6 root – n2= 3
Roots are different so edge is inserted in spanning tree. Father of [3] = 4
Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 0 0 1 3 0 0 0

Step: 6 edge selected is 3 -5 wt = 7


n1 = 3 root – n1 = 4 n2= 5 root – n2= 4

Powered by iBirat Technologies <http://www.ibirat.com> 109


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Roots are same so edge is not inserted i


Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 4 0 1 3 0 0 0

Step: 7 edge selected is 2-5 wt = 8


n1 = 2 root – n1 = 2 n2= 5 root – n2= 4
Roots are different so edge is inserted Father of [4] = 2
Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 4 2 1 3 0 0 0

Step: 8 edge selected is 1-2 wt = 9


n1 = 1 root – n1 = 2 n2= 2 root – n2= 32
Roots are same so edge is not inserted
Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 4 2 1 3 0 0 0

Step: 9 edge selected is 2-3 wt = 10


n1 = 2 root – n1 = 2 n2= 3 root – n2= 2
Roots are same so edge is not inserted
Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 4 2 1 3 0 0 0

Step: 10 edge selected is 5-7 wt = 11


n1 = 5 root – n1 = 2 n2= 7 root – n2= 7
Roots are different so edge is inserted in spanning tree. Father of [7] = 2
Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 4 2 1 3 2 0 0

Step: 11 edge selected is 5-8 wt = 12


n1 = 5 root – n1 = 2 n2= 8 root – n2= 8
Roots are different so edge is inserted in spanning tree. Father of [8] = 2
Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 4 2 1 3 2 2 0

Step: 12 edge selected is 7-8 wt = 14


n1 = 7 root – n1 = 2 n2= 8 root – n2= 2
Roots are same so edge is not inserted
Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 4 2 1 3 2 2 0

Step: 13 edge selected is 5- 9 wt = 15


n1 = 5 root – n1 = 2 n2= 9 root – n2= 9
Roots are different so edge is inserted in spanning tree. Father of [8] = 2

Powered by iBirat Technologies <http://www.ibirat.com> 110


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Node:- 1 2 3 4 5 6 7 8 9
Father:- 4 0 4 2 1 3 2 2 2

0 3
2

4 0 6

8
7 9

Since, minimum spacing tree should contain n-1 edges where n is the no. of nodes in the
graph. This graph contains nine nodes so after inserting 8 edges in the spanning tree we will
not examine other edges & stop the process.

Here, edge included in the spacing tree are (1, 5) (4, 5) (3, 6), (5, 6), (2, 5) ,(5, 7), (5,
8) & (5, 9) & weight of spanning tree = 2 + 3+ 5+ *+ 11+12 + 15
` = 62

Round- Robin algorithm:-


Initialize the spanning forest to contain the node but not edges.
1. the node but not edges.
a. Each vertex is in It’s own set called partial tree & maintained in aqueue
arbitrarly.
2. maintain each edges associated with each node or partial tree in priority queure
ordered by the weight of the edges.
3. Select a partial tree from queue & find the minimum weight edge incident to the
partial tree from priority queue.
4. find the partical tree that is connected by minimum path edge. Remove two sub tree
joining by the edge & combine in to a single new tree & add to rear of the queue.
b. Combine two priority queue of the node A & B (partial tree ) & delete the
edge connecting them from queue.
5. Repeat the algorithm unit a queue contain a single tree which is called minimum
cost spanning tree.

0
0 28
10 1
10 1
5 16
5 16 14
14 6
6 25
25 2
2
24 18 4
4 12
12 22 0
22 0
Soln:-
Priority queue. Partial tree weight of edges.

Powered by iBirat Technologies <http://www.ibirat.com> 111


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

{4} 22, 24, 25


{3} 12, 18 22
{5} 10, 25
{6} 14, 18, 24
{0} 10, 28
{2} 12, 16
{1} 14, 16, 28

{3, 4} 12, 18, 24, 25


{0, 5} 25, 28
{1, 6} 16, 18, 24, 28
{2, 3, 4} 16, 18, 24, 25
{0, 2,3, 4, 5} 16, 18, 24, 28
{0, 1, 2, 3, 4, 5, 6} all cancel

Here, weight of spaning tree = 10+25+22+12+16+14 =99

Greedy algorithm:-
Consider the problem of making changes Assume coines of value 25 (quarter), 10
& (dine), 5 (nick) , & 1 (penny) & suppose we want to return 63 in change, almost
without thinking , we convert this amount to two quarters, one dine & 3 pennies. Not only
wher we able to determine quickly lost of coins & the correct value but we produce certain
list of value with that coin.
The algorithm probably used to select the largest will whose value was not greater
than 63, & add it to the list of subtract it’s value from 63 getting 38[(63-25) = 38]
We then select the largest coi9n whose value is not greater than 38 and add it to the
list & so one. According to this
63-25 = 38
38-25 = 13
13-10 = 3
3-1 =2
2-1 =1
1-1 = 0
This method of making charge is a greedy algorithm.
At any individual stage a greedy algorithm selects that option which is locally
optimum in same some particular sence. not that the greedy algorithm for making change
produces on over al optimum solution only because of special properties of the coins. If the
coins had value 1, 9 & 11 & we first select an 11 coin & then four 1 coins total of 5 coins.
We have seen several greedy algorithm such as Dijkstrals shortes path algorithm &
kruskal’s minimum cost spanning tree algorithm.
Kruskal’s algorithm is also greedy as it picks from remaining edges the shortest
among these that do not create a cycle.

Powered by iBirat Technologies <http://www.ibirat.com> 112


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

/*Program of stack using Array */


# define max 5
Int top =-1;
Int stack_arr[Max];
Main()
{
Int choice;
While(1)
{
Printf(“1.psh”\n”);
Printf(“2.pop”);
Printf(3. display”);
Printf( 4. quit”);
Printf(“Enter your choice”)
Scanf(“%d”, choice);
Switch(choice)
{
Case 1:- psh();
Break;
Case 2: pop();
Break;
Case 3:- display()l;
Break;
Case 4: exit(4);
Default:
Printf(“wrong choice”);
}
}
}
Void push()
{
Int pushed_item;
If(top== (max -1)
Printf(“stack overflow”);
Else
{
Printf(“Enter that item to be pushed in stack”);
Scanf(“%d”, & pushed_item);
Top =top +1;
Stack_arr[top] = pushed_item;
}

Powered by iBirat Technologies <http://www.ibirat.com> 113


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

}
Void pop()
{
If (top = =-1)
Printf(“stack uinderflow”);
Else
{
Printf(“popped element is %d”, stack_arr[top];
Top = top -1;
}
}
Void display()
{
Int I;
If(top == -1)
Printf(“Stack empty”);
Else
{
Printf(“Stack element”);
For(i=top; I > = 0; i- -)
Printf(“%d”, stack_arr[i]);
}
}

/*Program of circular queue */


# define Max 5
Int cqueue_arr[Max];
Int front =-1;
Int rear =-1;
Main()
{
Int choice;
While (1)
{
Printf(“1. insert”);
Printf(2.delete”);
Printf(3.dispalay”);
Printf(4.quit”);
Printf(“Enter your choice”);
Scanf(“%d”, & choice);
Switch(choice)
{
Case 1: insert();

Powered by iBirat Technologies <http://www.ibirat.com> 114


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Break;
Case 2: del();
Break;
Case 3: display();
Break;
Case 4: exit(1);
Default:
Printf(“Wrong choice”);
}}}
Insert()
{
Int added_item;
If((front = = 0 & & rear = = Max -1)) || (front = = rear +1))
{
Printf(“Queue overflow”);
Return;
}
If (front = = -1)
{
Front = 0;
Rear = 0;
}
Else
If (rear = = max -1)
Return =0;
}
else
Reae = rear +1;
Printf(“I/P element for insertion in queue”);
Scanf(“%d”, & added_item);
Cqueue_arr[rear] = added item;
Dle()
{
If(front ==-1)
{
Printf(“Queue underflow”);
Return;
}
Printf(“Element deleted from queue is %d”, cqueue_arr[front]);
If (front == rear)
{
Front =-1;
Rear =-1;

Powered by iBirat Technologies <http://www.ibirat.com> 115


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

}
Else
If(front = max-1)
Font =0;
Else
Front = front +1;
}
Display()
{
Int fornt _pos = front; rear_pos = rear;
If (front == -1)
{
Printf(“queue is empty”);
Return;
}
Printf(“Queue elements”);
If(front_pos<=rear_pos)
While(fornt_pos<=rear_pos)
{
Printf(%d”, cqueue_arr[front_pos]);
Front_pos + +;
}
Font_pos= 0;
While (front_pos<= rear_pos]);
Front_pos =0;
Whiel(frot_pos<=rear_pos)
{
Printf(%d”, cqueue arr[front_pos]);
Front_pos ++;
}}}

Output:-
1. insert
2. delete
3. display.
4. quit
enter Your choice:-1
input the element for insertion in queue 7
1. insert. 2. delete. 3. delete. 4. quit
enter your choice 1. input = 8
“ input = 9
+ input = 10
“ input = 11

Powered by iBirat Technologies <http://www.ibirat.com> 116


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

# Define Max 5
Int deque_arr[max];
Int left =-1;
Int right =-1;
Main()
{
Int choice;
Printf(“1. I/P restricted dequeue”);
Printf(“2. O/P restricted dequeue”);
Printf(“Enter your choice”);
Scanf(“%D”, & choice);
Switch(choice)
{
Case 1: input_que();
Break;
Default: printf(“Wrong choice”);
}}
Input_que()
{
Input_que()
{
Int choice;
While(1)
{
Printf(1. insert at right”);
Printf(2. delete from left”);
Printf(3. delete from right”);
Printf(4. display”);
Printf(5. quite”);
Switch(choice)
{
Case 1: insert_right();
Break;
Case 2: delete_left();
Break;
Case 3: delete_right();
Break;
Case 4: display_queue();
Break;
Case 5: exit();
Default: printf(“Enter wrong choice”);

Powered by iBirat Technologies <http://www.ibirat.com> 117


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

}}}
Insert_right()
{
Int added_item;
If((left == 0 && right == max -1) || (lseft == right +1))
{
Printf(“Queue overflow”);
Return;
}
If(left ==-1)
{
Left =0;
Right =0;
}
Else
(f(right = max-1)
Right =0;
Else
Right = right +1;
Printf(“I/P the element for adding in queue”);
Scanf(“%d”, & added_item);
Deque_arr[right] = added_item;
}
Insert_lfet()
{
Int added_item;
If(left== 0&& right = max -1) || (left = right +1));
{
Printf(“Queue overflow”);
Return;
}
If(left ==-1
{
Left = 0;
Right =0;
}
Else
If(left = 0)
Left = max -1;
Else
Left = left-1;
Printf(“I/P thelement for adding”);
Scanf(“%d”, & added_item);

Powered by iBirat Technologies <http://www.ibirat.com> 118


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Deque_arr(left) = added_item;
}
Delete_left()
{
If(left ==-1)
{
Printf(“Queue underflow”):
Return;
}
Printf(“Element deleted from queue is %d”, deque_arr[left]);
If(left == right)
{
Left =-1;
Right =-1;
}
Else
If()left== max-1)
Left =0;
Eles
Left = left +1;
}
Delete_right()
{
If(left ==-1)
{
Printf(“Queue under flow”);
Return;
}
Printf(“Element deleted from queue is %d”, deque_arr[right]);
If(left = = right)
{
Left = -1;
Right =-1;
}
Else
If(right = =0)
Right = max -1;
Else
Right = rightg -1;
}
Display_queue()
}

Powered by iBirat Technologies <http://www.ibirat.com> 119


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Program of list using array


#defince Max 10
Int arr[max];
Int n;
Main()
{
Int choice, item_pos;
While(1)
{
Print(“1. input list”);
Printf(“2. insert”);
Printf(“3. search”);
Printf(“4. display”);
Printf(“5. quit”);
Printf(“Enter your choice”);
Scanf(“%d”, & choce);
Switch(choice)
{
Case 1:
Printf(“Enter the no. of element to be inserted”);
Scanf(“%d”, &n)
Input(n);
Break;
Case 2:
Break;
Case 3. insert();
Break;
Case 3: printf(“Enter elements to be serched”);
Scanf(“%d”, & item);
Pos = search(item);
If(p0os>=1)
Printf(“%d found at postion %d”, item, pos);
Else
Printf(“element not found”);
Break;
Case 4:
Del();
Break;
Case 5: display();
Break;
Case 6: exit();
Break;

Powered by iBirat Technologies <http://www.ibirat.com> 120


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Default:
Print(“Wrong choice”);
}}}
Input()
{
Int I;
For (I =0; i<n; i++)
{
Printf(“I/P value for element %d”,j+1);
Scanf(%d”, &arr[i]);
}}
Int search *(int item)
{
Int I;
For (I =0; i<n;i++)
{
If (item == arr[i])
Return(i+1);
}
Return(0) /*if element not found */
}
Insert ()
{
Int temp, item, position;
If(n == max)
{
Printf(“list overflow”);
Return;
}
Printf(“enter positionfor insertion”)
Scanf(“%d”, & position);
Printf(“Enter the value”);
Scanf(“%d”, & item);
If position > n+1)
{
Printf(“Enter position less than or equal to n+1);
Return;
}
If position = n+1;
}
Arr[n] = item
n = n+1
return;

Powered by iBirat Technologies <http://www.ibirat.com> 121


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

}
/*insertion in between */
Temp = n-1;
While (tem> = posiotn-1)
{
Arr[tem +1] = arr[temp];
Temp --;
}
Arr[position -1] = item;
n = n+1;
}
Del()
{
Int tem , position, item;
If(n==0)
{
Printf(“list underflow”);
Return;
}
Printf(“Enter the element to be deleted”);
Scanf(“%d”, & item)
If (item = arr[n-1])
{
N = n-1;
Retun;
}
Position = search (item);
If (position == 0)
{
Printf(“Element not present in array”);
Return;
}
//Deletion in between
Temp = position -1;
While (tem<=n-1)
{
Arr[temp] = arr[temp +1];
Temp ++
{
N = n-1;
}
Display()
{

Powered by iBirat Technologies <http://www.ibirat.com> 122


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Int I;
If (n = = 0)
{
Printf(“List is empty”);
Return;
}
For (I =0; i<n; i++)
Printf(“value at position % %d”, i+1, arr[i]);
}

/* program of single linked list */


#include <stdio.h>
#include<malloc.h>
Struct node
Int info;
Struct node * link;
}* start;
Main()
{
{
Int choice n, m, position, I;
Start = NULL;
While(1)
{
Printf(“1. create list \n”);
Printf(“2. ad at beginning \n”);
Printf(“3. add after \n”);
Printf(“4. delete \n”);
Printf(“5. display \n”);
Printf(“6. count \n”);
Printf(“7. reverse \n”);
Printf(“8. search \n”);
Printf(“ 9. quit \n”);
Printf(“Enter your choice”);
Scanf(%d”, & choice);
Switch (choice)
{
Case 1: printf(“How many nodes you want”);
Scanf( “%d”, & n);
For(i=0; i<n;i++)
{
Printf(“Enter the element :”);

Powered by iBirat Technologies <http://www.ibirat.com> 123


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Scanf(“%d”<&m);
Create – list (m);
}
Break
Case 2:
Printf(“Enter the element:-“);
Scanf(“%d”, & m);
Addetheg(m);
Break;
Case 3:
Printf(“Enter the element:-“);
Scanf(“%d”, &m);
Printf(“Enter the position after which this element is );
Scanf(“%d”, & position);
Add after (m, position);
Break;
Case 4:
If(start = = NULL)
{
Printf(“List is empty \n”);
Continue;
}
Printf(“Enter the element for deletion “);
Scanf(‘%d”, &m)
Del(m);
Break;
Case 5: display();
Break;
Case 6: count();
Break;
Case 7: rev();
Break;
Case 8:
Printf(“Enter the element to be searched”);
Scanf(“%d”, &m);
Search(m);
Break;
Case 9:
Exit()
Default: printf(“Wrong choice \n”);
} /* end of switch */
} /* end of main() * /
Create – list (int data)

Powered by iBirat Technologies <http://www.ibirat.com> 124


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

{
Struct node *q, * temp;
Temp = malloc (size of (struct node));
Temp – info = data;
Temp – link = NULL;
If(start == NULL) /*if list is empty*/
q = start;
While(q link ! = NULL)
q = q link;
q link = temp
}
Return;
} /* end of create – list is */
Addatbeg (int data)
{
Strct node * temp;
Temp = malloc (size of (struct node));
temp infor = data;
temp link = start;
start = temp ;
return;
} /* End of addatbeg() */
Add after (int data, int pos)
{
Struct node * temp *q;
Int I;
Q start;
For (i=0; i<pos-1; i++)
{
Q = q link;
If(q == NULL)
{
Printf(“There are less than %d element”, pos);
Return;
}} /* end of for */
Temp = malloc (size of (struct node)
Temp link = q link;
Temp info = data;
Q link = temp;
Return;
} /*end of add after () */
Del (int data)
{

Powered by iBirat Technologies <http://www.ibirat.com> 125


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Struct node * temp, * q;


If(start info = = data)
{
Temp = start;
Start start link; /* first element deleted */
Free (temp);
Return;
}
Q = start;
While (q link link ! NULL)
{
If (q link info = = data)
{
Temp = q link;
Q link = temp link;
Free (temp);
Return;
}
Q = q link ;
/*end of while */
If (q link info = data) /* last element deleted */
{
Temp = q link ;
Free (temp);
Q link = NULL
Return;
}
Printf(“element %d not found \n”, data);
Return;
} /* End of del() */
Display()
{
Strcut node * q;
If (start == NULL)
{
Printf(“List is empty \n”);
Return;
}
q = start
printf(“List is: \n”)
while (q ! = NULL)
{
Printf(“%d”, a info);

Powered by iBirat Technologies <http://www.ibirat.com> 126


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Q = q link;
}
Printf(“\n”);
Return;
} /*End of display */
Count()
{
Struct node * q = start;
Int cnt = 0;
While (q ! = NULL)
{
Q = q link;
Cnt ++ ;
}
Printf(“No. of element are %d \n”, cnt);
} /* End of count () */
Rev()
{
Struct node * P1, *P2, *P3;
If (start link = = NULL) / *only one element */
Return;
P1 = start;
P2 = P1 link
P3 = P2 Link;
P1 Link = NULL
P2 link = P1;
While (P3 ! = NULL)
{
P1 = P2;
P2 = P3;
P3 = P3 link
P2 link = P1;
}
Start = P2;
} /*End of rev() */
Search(int data)
{
Struct node * ptr = start;
Int pas = 1;
While (ptr ! = NULL)
{
If (ptr infor == data)
{

Powered by iBirat Technologies <http://www.ibirat.com> 127


Resource downloaded from http://pu.ibirat.com
iBiratPUSL http://pu.ibirat.com
Student Online Resource – Digital Library System [email protected] - [Queries]
[email protected] - [Send Document]

Printf(“Item %d found at position %d”, data, post);


Return;
}
Ptr = ptr link;
Pos + + ;
}
If (ptr = = NULL)
Printf(“Item %d not found in list \n”, data);
} /* end of search() */

Powered by iBirat Technologies <http://www.ibirat.com> 128


Resource downloaded from http://pu.ibirat.com

You might also like