Anda di halaman 1dari 69

Royal Education Preparation without Parents Blessing is Stack without Top

DFS (Data File Structure)


Instruction-: There are certain questions whose page numbers
are mentioned so please refer to the page numbers specified
for those answers, polynomial and arrays problems releasing
soon)
Note-: This booklets is prepared for private use for reading to
SYBCA students of Royal Education sale of this material is
prohibited)
Q.1 If application does not have predefined memory
requirement, array is a suitable data structure. State (T/F)
False-: if there is no predefined memory requirement link list
(dynamic) implementation is suitable data structure.
Q.2 Give example of primitive data structure. Or explain
primitive and non-primitive data structure.
It is a data structure which is directly operated upon Machine level
instruction.
E.g. Number system, integer, character, pointer, real no.
+ PRIMITIVE :-
(If this question asked in 3 marks then explain below)
(I) Number system:-
Numbers are used symbolically to represent quantities.
There are various Methods of representing quantities.
Tally symbol
Roman no. system.
Positional no. system.
(II) Integer:-
A quantity representing object which are discrete in nature.
i.e. no. of object are countable can be represented by an integer.
The integer is Positive or Negative. There are many methods to
represent an integer. They are
(a) Sign and magnitude method :-
This method is used to represent a negative no. write
negative no. it is necessary to a sign symbol in front of no.
(b) Radix complements Representation.
(c) 2s complement Representation
(d) Diminished Radix complement Method
(III) Real no:-
Fixed point rotation is sufficient to represent most of real no.
Normally arising when computations re performed on a computer.
There are various methods to represent real no.
(1) Floating point to or scientific notation.
(2) Multiple-precision program package.
(3)Binary based floating point.
1 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
(IV)Character:-
The first computer programs were written in a machine code.
Machine code programming was cumbersome and the programs were
difficult to read and correct.
To overcome this problem symbolic code were developed to
represent information items that were Character rather than
numeric in nature.
ASCII:-
It was developed as a standard coding scheme for
computer.
EBCDIC:-
It is character coding scheme system used primarily on
IBM 3030 series of computer.
+ NON PRIMITIVE :-
The data structure which is derived from the primitive data
structure is called non-primitive data structure. This data structure is
not directly operated upon machine level instruction.
Q.3 Write a short note on list
List is a set of variable number of element. There are two types of
list.
(1) Linear list (2) Non linear list.
(1) Liner list:-
If the element of list contain is having relationship of adjacency then
such list is said linear list.
(2) Non liner list:-
If list is not liner then such list is called non liner list.
Q.4 Explain the importance of data structure in brief.
Data structure is the possible ways of organizing data items
that defines how the data items are stored in memory and
relationship with each other.
Data structure is the possible ways that defines the
relationship between data items.

Q.5 Given a 1-dim array A[1:100] where B=1000 and s =4
Bytes. Calculate the address of A [98]. Address A[i] =M+ (i-L)
* w
Where M is the starting address is the size of the word, I is the
element
1000+ (98-1)*4
1000+388
1388
Q.6 Write a shot note on one dimensional array.
One dimensional array
2 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Array is a group of related data item that store in a common name,
they have same data type for all elements. In array, number of data
items arranged contiguously in memory. The array is a most
commonly used data structure, in to most programming language.
Array is also subscript variable, and index number is called subscript
number. Always array is start from index number 0 to last element is
(index number 1)
An array is also called linear data structure. There exists a linear
relationship between the array elements, the array elements lie in the
computer memory in linear fashion.
Arrays are ordered and unordered arrays. In unordered array, data
is not sorted in ascending or descending order. But in ordered array,
data is sorted in ascending or descending order. This arrangement
makes possible a fast ways of searching for a data item.
The major advantage of ordered array is that search times are much
faster than in an unordered array. The disadvantage of ordered array
is that insertion takes longer times because all the data items with a
higher key value must be moved up to make room, deletion are slow
in both ordered and unordered arrays because items must be moved
down to fill the hole left by the deleted item.
So, ordered arrays are therefore useful in situation where searches
are frequent, but insertion and deletions are not more.

Q.7 Write down the formulae for finding out the address of
single dimensional Array?
Where Lo is called base address or starting address of array.
The address of element A [i, j] can be find out by using following
equation.
Lo + (j-1) * 2+i -1, where I = row index no.
J = column index no.
For element A[1,4], address = L+6.
Q.8 Given a 1-dim array A [..-5..100] where b=1000 and s=4
bytes. Calculate the address of A [98] and also find the total
memory required to store the entire array and the size at the
array.
Aj =L
0
+ C * (i-b)
=1000+4 * (98-(-5))
=1000+412
=1412
Array size=u-b +1
=100-(-5) +1
=106
3 Royal Education-SYBCA Material
L
0
=starting location
C=size
i =98 location
b=base address
u=Upper limit
b=Lower limit
Royal Education Preparation without Parents Blessing is Stack without Top
Total memory required=Array size *4
=106*4
=424 bytes
Q.9 Give an array x [-3:4,-4:2] at type integer.
1) Find total number of element in x.
2) What is the size of array x?
3) If the base address is 1001, find the address of x[-2,-3].
4) What is the address of last element?
1) Total no of element = (u1-b1+1)*(u2-b2+1)
= (4-(-3) +1)*(2-(-4) +1)
= (8*7)
=56
2) Size of array=Total element *2
=56*2
=112bytes
3) Base address is 1001=0
X [-2,-3] =B+ (i-b
1
) * (u
2
-b
2
+1) + (j-b
2
)*2
=1001+ ((-2)-(-3))*(2-(-4) +1) + (-3-(-4))*2
=1001+1*7+1*2
=1001+ (8*2)
=1017
X [4,2] =1001+ (i-b
1
) * (u
2
-b
2
+1) + (j-b
2
)*2
=1001+ (4-(-3))*(2-(-4) +1) + (2-(-4))*2
=1001+ (55*2)
=1111
Q.10 Consider an array A [-25...19]
Find out the number of elements in the array.
No. of elements = (u-b+1)
=19-(-25) +1
=45
Q.11 An array A [-10:2,-4:4] is stored in memory. Count the
total number of element in an array A.
Total number of element= (u
1
-b
1
+1)*(u
2
-b
2
+1)
Q.12 Array A (12:50, 3:30) is given. Base address B=1600 and
word size=2 byte. Find the address at A (35, 23) for both row
major and column major and also find number of rows and
columns in the given matrix.
Row Major
A (35, 23) =1600+ ((i-b1)*(u2-b2+1) + (j-b2))*2
=1600+ ((35-12)*(30-3+1) + (23-3))*2
=1600+ (803*2)
4 Royal Education-SYBCA Material
b1 =-3
b2=-4
u1=4
u2=2
Royal Education Preparation without Parents Blessing is Stack without Top
=3206
Q.13 For the given 2d-integer array A, Find out an address of A
[2, 2]
Where 0<=i<=2
1<=j<=2
And the address of first element of an array is 1000.
A [2, 2] =1000+ ((i-b1)*(u2-b2+1) + (j-b2))*2
=1000+ ((2-0)*(2-1+1) + (2-1))*2
=1000+ (5*2)
=1010
Q.14 In array B [-1..2, 2..4] integer data has been stored in
column major order. Find out the memory location for B [0]
[3]. Starting memory location is 1209.
A [2, 2] =1209+ ((j-b2)*(u1-b1+1) + (i-b1))*2
=1209+ ((3-2)*(2-1+1) + (0-(-1)))*2
=1209+ (5*2)
=1219
Q.15 With suitable diagram, show how elements are stored in
memory linearly, both in row major order and column major
order.
Or
Write down the formulae for finding out the address of two
dimensional arrays.
A two dimensional array have n rows and m columns (which is stored
by column), the general form of finding the address of element A[i,j]
is,
Lo + (j-1) * n + (i-1)
What is row major order?
A two dimensional array can be stored sequentially row-by-row
(called row major ordered) is represent as below,
(1,1) A(1,2).A(1,m) A(2,1).A(2,m) A(n,1)..A(n,m)
The address of array element A[i,j] is,
Lo + (i-1) * m+ (j-1)
What is column major ordered
A two dimensional array can be sorted sequentially column-by-
column (called column major ordered) is represent as below,
A(1,1)A(2,1)A(n,1)A(1,2)A(2,2)A(n,2)A(m,1)A(m,2)
...A(m,n)
The address of array element A[i,j] is,
Lo + (j-1) * n+ (i-1).
5 Royal Education-SYBCA Material
A
11
A
12
A
13
A
14
A
21
A
22
A
23
A
24
A
31
A
32
A
33
A
34
Royal Education Preparation without Parents Blessing is Stack without Top
Q.16 Define transpose of an array.
The transpose of a two dimensional array is obtained by
reversing the subscript positions. The transpose of mxn array is
n x m. It is denoted by B
T
.
Eg: B (3, 8) =B
T
(8, 3)
Q.17 What is a cross-section of an array?
A cross-section of an array is obtained by holding any one of
the subscripts constant while varying the other through
its entire range of values.
Q.18 What is a sparse matrix?
In a 2 dimensional array the density of zero elements is
relatively high, is called as a sparse array. The types of sparse
matrices are
a) Triangular matrices
Lower
i. Lower-left
ii. Lower-right
6 Royal Education-SYBCA Material
A11
A12
A13
A14
A21
A22
A23
A24
A31
A32
A33
A34
A11
A21
A31
A12
A22
A32
A13
A23
A33
A14
A24
A34
Row major order
Column major order
Royal Education Preparation without Parents Blessing is Stack without Top
Upper
i. Upper-left
ii. Upper-right
b) Band matrices
Diagonal
Tridiagonal
Alpha-Beta Band
Take the print from Pg.23 of D.Samanta
Q.19 Explain the two classic data structure linear and non
linear.
Ans) Classic data structure is classified into two main classes linear
data structure and non linear data structure. In Linear data structure
all the elements form a sequence or maintain a linear ordering.
In non linear data structure all the elements are distributed over a
plane.

Array [m, n] is arranged by row in memory. The base address
is B. The element sizes 5 bytes. Find out the starting address
of Array [i,j].Also find out the number of elements in an
array.

Q.20 Difference between list and array.
LIST
(1) List is an ordered set of
element.
(2) It consists of variable number
of element.
(3) Insertion and deletion can be
can not be performed on list.
(4) List is not always called
array.
(5) There are two types of list.
(i) Liner list
(ii) Non liner list
ARRAY
(1) Array is an unordered set of
element.
(2) It consists of fixed no. of
element.
(3) Insertion and deletion
performed on list.
(4) Array is always called list.
(5) There are two types of Array.
(i) Single dimensional
(ii) Multi dimensional
Q.21 Write a short note on triangular array/matrix.
7 Royal Education-SYBCA Material
Classic data structure
Linear data structure Non-linear data structure
Arrays
Link list
Stacks
Queues
Trees
Graphs
Tables
Sets
Royal Education Preparation without Parents Blessing is Stack without Top
In a 2D array where all elements below or above the diagonal are
zero is called triangular array. There are two types of triangular array.
a) Upper triangular array Elements in an array where all
elements below the diagonal are zero is called an upper
triangular array.
b) Lower triangular array Elements in an array where all
elements above are zero is called lower triangular array.
QUESTIONS
1) Given a 1-dim array A[-5100] where b=1000 and s=4 bytes.
Calculate the address of A[98] and also find the total memory
required to store the entire array and the size of the array.
2) Consider an array A[-2519]. Find out the number of elements
in the array.
3) Write algorithm for insertion and deletion in a queue using
array.
6) define: upper bound of an array.
7) What is an array? Explain memory representation of an array.
8) Write an algorithm to search an element from the given 1-d array
A.
9) for the given 2-d integer array A, find out an address of A[2,2].
Where
0<=i<=2, 1<=j<=2 and the address of first element of an array is
1000.
10) Trace merge sort algorithm to sort an array A={66,12,45,3}.
11) search an element 66 from the given array A={66,12,45,3}.
12) represent the stack using array.
SORTING
write an algorithm for quick sort.
Introduction:
Quick sort is one of the most efficient sorting methods. It is also
referred to as partition exchange sort. This sort is suitable for large
tables. The main priority of this sort is to place a particular element in
its final position within the table.
This technique partitions the table into TWO sub-tables. The
object of partition is to allow a specific element to find its proper
position with respect to the others in the sub-array. A particular
element is preceded by all smaller values and followed by all larger
values. This same process is repeated until all elements of the sub-
tables are placed in their final positions.
An example:
Let A be an element from a specific position within the array of
N number of elements. Suppose that the elements of N are
8 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
partitioned such that A element is placed at position J and the
following condition holds:
Each of the elements from 1 to J-1 is less than or equal to A.
Each of the elements from J+1 to N is greater than or equal to A.
If this two conditions hold true for a particular,
element A than it can be applied to the two sub-tables until all
elements are placed in their sorted order and the result is a sorted
file.
A Practical Example:
Suppose the initial array N contains 12 elements, (i.e. N=12).
The unsorted list is as follows:
44 33 11 55 77 90 40 60 99 22 88 66
Step 1: scanning from right to left
44 33 11 55 77 90 40 60 99 22 88 66

Here we consider 44 as a particular element and try to find
out its final position. Starting to compare 44 with numbers
from right to left until a number smaller than 44 is found.
While scanning from right to left the first smallest number
found is 22. So the table is read as:
44 33 11 55 77 90 40 60 99 22 88 66
Scanned-number
Step 2: Scanning from left to right.
44 33 11 55 77 90 40 60 99 22 88 66
Here, start the comparison of 44 with number by scanning the list
from left to right, and from the first element onwards. When a
number larger than 44 is found stop there. While scanning from left
to right the larger number scanning from left to right is 55. So the
table read as:
44 33 11 55 77 90 40 60 99 22 88 66
45
Larger smaller
Step 3: Interchange larger and smaller.
44 33 11 22 77 90 40 60 99 55 88 66

Interchange of 22 and 55.
Step 4: Scanning from right to left. |
9 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
44 33 11 22 77 90 40 60 99 55 88 66
Start the comparison of 44 with numbers by scanning the list from
right to left, excluding the element 55. When a first smaller number is
found, stop there. Here the smaller number is 40. So the table is as
follows:
44 33 11 22 77 90 40 60 99 55 88 66
Scanned number
Step 5: scanning from left to right.

44 33 11 22 77 90 40 60 99 55 88 66
44 33 11 22 77 90 40 60 99 55 88 66
|larger | smaller
Step 6: Interchange larger and smaller.
44 33 11 22 40 90 77 60 99 55 88 66
40 and 77 interchanged.
Step 7: Scanning from right to left.
44 33 11 22 40 90 77 60 99 55 88 66
After Scan:
44 33 11 22 40 90 77 60 99 55 88 66

40 and 44 will be swapped and both pointers meet at a point.
Step 8: interchange
40 33 11 22 44 90 77 60 99 55 88 66.
At this stage, the particular element 44, is placed in its furniture
during final position. All the elements on the right side of 44 is
greater than 44. All elements on the right side of 44 are smaller
than 44.
Now the whole table is divided into two sub tables or partition.
Left partition has got 4 elements and right partition has got 6
elements. We can apply the same process repeatedly until the two
sub-tables are fully sorted.
To scan the list form Right to Left and from Left to Right we
require another two index variables, namely j and I. Initially j and I are
set to ub and lb. Where ub=upper bound and lb=lower bound.
10 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
When the element is placed in its final position then scanning
the list will be terminated to the final location of the particular
element itself. At this time the values of I and j will be equal.
Considering the above example when 44 is placed in its final place, at
that time I and j will be 5. so I=j=5.
Quick sort can also be performed recursively. The
algorithm for this is as follows:
Find out the final place of the particular element of the current
table.
Invoke the quick-sort to sort the left sub table.
Invoke the quick-sort to sort the right sub table.
+ APGORITHEM for Quick sort : -
Quick sort (K, LB, UB)
Purpose To sort the table in ascending order using quick sort.
K Represents the vector of N records.
LB Represents the Lower bounds of the current sub table being
processed.
UB Represents the Upper bounds of the current sub table being
processed.
KEY Represents the key value which is being placed in its final
position within the sorted sub table.
FLAG Represents the logical variable which indicates the end of the
process that places record in its final position.
1. [Check if table size greater than one]
if LB UB
Then return
2. [Initialize]
KEY K[LB]
I LB+1
J UB
3. [Search left and right way]
While i<j do
While KEY K[i] do
i=i+1
While KEY K [J]
j j-1
K [I] K [J]
4. [Place element into final position]
KEY K[j]
K [LB] K[j]
5. [Perform Quick sort on first sub table]
Call Quick sort (K, LB, j-1)
6. [Perform Quick sort on second sub table]
11 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Call Quick sort (K,j+1,UB)
7. [Finished]
Return
Q.Write an algorithm for selection sort.
Selection sort(K,N)
1. [Loop on pass index]
Repeat thru step 4 for PASS=1,2,..N-1
2. [Initialize minimum index]
Min_indexPASS
3. [Make a pass and obtain element with smallest value]
Repeat for I=PASS+1,PASS+2,.N
If k[I]<k[Min_index]
then Min_index I
4. [Exchange elements]
If Min_index!=PASS
then k[PASS]k[Min_index]
5. [Finished]
Return
5) write an algorithm for insertion sort method.
INSERTION SORT
This method is widely used by all card players.
Considering first card. Second card is inserted in its proper place left
or right of 1
st
cars. Then card is inserted in its proper place on left of
1
st
or in between 1
st
and 2
nd
or on right of 2
nd
card.
+ ALGORITHEM for insertion sort :-
INSERTION-SORT (l, n)
Purpose To sort the table using insertion sorting
l Represents the list of elements.
N Represents the number of element in the list.
1. [Initialize]
l[0]= -0
2. [Repeat through step 3 to 5]
for i=1,2,3,.n
3. (i) temp = l[i]
(ii) pointer = l-1
4. [while (temp<l[pointer])]
(i) l [pointer+1]=l[pointer]
(ii) pointer = pointer 1
5. [l[pointer] = temp]
6. [finished]
Return
EXAMPLE OF INSERTION SORT
Unsorted: 44 33 11 55 77 90 40 60
12 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top

Pass 1: 44 33 11 55 77 90 40 60
Pass 2: 33 44 11 55 77 90 40 60
Pass 3: 11 33 44 55 77 90 40 60
Pass 4: 11 33 44 55 77 90 40 60
Pass 5: 11 33 44 55 77 90 40 60
Pass 6: 11 33 44 55 77 90 40 60
01 Pass 7: 11 33 40 44 55 77 90 60
Pass 8: 11 33 40 44 55 60 77 90
An insertion sort is one that start a set of record by inserting
records into an existing sorted file in order to find the correct
position. We have to search the file till and item less than the target
item is found all the other compare item are moved down the list and
the target is inserted into the bacated sort.
6) Sort the given data using selection sort 28,
35,43,20,15,18,17,36
7) create max heap tree and do the heap sort for the data given
below.
21,46,34,85,50,33,87,64,14,19,2
(2) Merge sorting :-
The operation so sorting is closely related to the process of
merging.
First examine the merging of two ordered tables which can be
combined to produce a single sorted element (table).
This process can be accomplished easily by successively selecting
the record with the smallest key occurring i either of the tables and
placing this record in a new table, there by creating an ordered list.
For example, from the tables
Table 1. 11 23 42
Table 2. 9 25
We obtain the following TRACE.
Table 1. 11 23 42
Table 2. 25
NEW TABLE 9
Table 1. 23 42
Table 2. 25
NEW TABLE 9 11
13 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Table 1. 42
Table 2. 25
NEW TABLE 9 11 23
Table 1. 42
Table 2.
NEW TABLE 9 11 23 25
Table 1.
Table 2.
NEW TABLE 9 11 23 25 42
Note that the two ordered tables can be assumed to be stored in a
common vector. The two tables in the current examples could be
stored in a vector k as follow.
K : 11 23 42 9 25
FIRST SECOND THIRD
Where the FIRST through the SECOND-1 ele. and SECOND through
the THIRD ele. represent the first and second table respectively.
A temporary vector of the same size is required to hold the results of
performing a simple merge.
TEMP : 9 11 23 25 42
Where TEMP denotes a temporary vector of the same size as K.
+ ALGORITHEM for Merge Sorting : -
SIMPLE_MERGE (K, FIRST, SECOND, THIRD)
Purpose To sort the table in ascending order using simple merge
sorting.
K Two ordered subtables stored in a vector K with FIRST, SECOND,
and THIRD
TEMP Represents temporrary vector used in the merging
process.
i Represents the cursor associated with the first sub table.
j Represents the cursor associated with the second sub table.
L Represent the index variavle associated with the vector TEMP.
1. [Initialize]
iFIRST
j SECOND
L 0
2. [Compare corresponding elements and output the smallest.]
Repeat while i < SECOND and j THIRD
if K[i] K[j]
then L L+1
TEMP [L] k[i]
14 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
I i+1
else
L L+1
TEMP[L] K[j]
J j+1
3. [Copy the remaining element of non empty table]
if i SECOND
then Repeat
while j THIRD
LL+1
TEMP[L] K[j]
j j+1
Else Repeat
While i< SECOND
L L+1
TEMP[L] K[i]
i i+1
4. [Copy element in temporary vector in to original area.]
Repeat for i=1,2,..,L
K[FIRST-1+i]TEMP[i]
5. [Finished]
Return.
+ ALGORITHEM for Two way merge sorting : -
Two_way_merge_sort (K, START, FINISH)
Purpose Sorting using two ways merge sorting
K It is required to sort recursively its elements between position
START and FINISH.
SIZE represents the number of element in the current sub table to
be sorted.
MIDDKE represents the middle element of that suitable.
1. [Find out the size of the current sub table]
SIZE FINISH START+1
2. [Check if single element]
If SIZE 1
Then return
3. [Calculate the midpoint position of current sub table.]
MIDDLE START + [SIZE/2]-1
4. [Call two way merge sort for first table]
Call Two_way_merge_sort(K,START,MIDDLE)
5. [Call two way merge sort for second sub table]
Call Two_way_merge_sort (K, MIDDLE+1, FINISH)
6. [Apply Simple merge to sub table]
Call Simple merge (K, START, MIDDLE+1, FINISH)
7. [Finished]
Return
15 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
INSERTION-SORT (l,n)
Purpose To sort the table using insertion sorting
l Represents the list of elements.
N Represents the number of element in the list.
1. [Initialize]
l [0]= -0
2. [Repeat through step 3 to 5]
for i=1,2,3,.n
3.(i) temp = l[i]
(ii) pointer = l-1
4. [while (temp<l[pointer])]
(iii) l [pointer+1]=l[pointer]
(iv) pointer = pointer 1
5. [l[pointer] = temp]
6. [finished]
Return
(3) Bubble sort :-
Bubble sort differs form the selection sort in that instead of finding
the smallest record and then performing an interchange, two records
are interchanged immediately upon discovering that they are out of
order.
In this method at most n-1 passes required during the first pass
k1and k2 are compared, and if they are out of order, then records R1
and R2 are interchanged.
This process is repeated for records R1 and R2, R3, and R4 and so
on. This method will cause record with small keys to move or bubble
up. After the first pass, the record with the largest key will be in the
nth position.
On each successive pass, the records with the next largest key will
be placed in position n-1, n-2, respectively, thereby resulting in a
record is a sorted.
ALGORITHEM for bubble sort:-
BUBBLE_SORT (K, N)
PurposeTo sort the table in ascending order using Bubble sort.
KRepresents the list of the elements.
NRepresents the size of the list.
PASS Represents the pass counter.
LAST Represents the position of the last unsorted element.
EXCHAS Used to count the number of exchange made on any pass.
i Used as to index the vector elements.
1. [Initialize]
LASTN (entire list assumed unsorted at this point)
2. [Loop on pass index]
Repeat through step 5
16 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
For PASS = 1,2,..,N-1
3. [Initialize exchange counter for this pass]
EXCHAS 0
4. [Perform pair wise comparisons on unsorted]
elements
Repeat for i=1,2,..,LAST-1
if K[i] >K[I+1]
then K[i] K[I+1]
5. [Check if sorted]
if EXCHAS = 0
then return
else LAST LAST-1
6. [Finished]
Return
Q Complexity of some generally used algorithms:
Algorithm Worst Case Average Case
Linear Search O(n) O(n/2)
Binary Search O(log n) O(log n)
Bubble Sort O(n
2
) O(n
2
)
Quick Sort O(n
2
) O(n log n)
Insertion Sort O(n
2
) O(n
2
)
Selection Sort O(n
2
) O(n
2
)
Merging
Algorithm
O(n) O(n)
17 Royal Education-SYBCA Material
ALGORITHAM OF BINARY
SEARCHING
Royal Education Preparation without Parents Blessing is Stack without Top
SEARCHING
Q.1 DIFFERENCE BETWEEN LINEAR SEARCH AND BINARY
SEARCH:
Searching is a technique used to find out particular element from
the list. There are several techniques are used to find out element
from the list.
Linear search or sequential search is a method to find out particular
element from the list. In linear searching we are starting from the
start of the list and check for each and every element whether that
element is required element or not. If that element is our required
element than its position is printed otherwise at the last message has
been given your element has not found in list. In linear search there is
no need to list should be sorted. But it requires more time because
each and every elements are processed for searching.
There is also another method to search particular element that is
Binary search. In binary searching entire list is in sorted order. In this
method we check the middle element of the list. If the middle
element is our required element than search method is end otherwise
if middle element is less than our required element than we have to
proceed in same way in second half portion of list. If middle element
is greater than required element than we have to proceed in same
way in first half portion of list.
Q.2 When we can use linear search and binary search
An unsorted array is searched by linear search that scans the array
elements one by one until the desired element is found. If the array is
sorted we can employ binary search, which brilliantly halves the size
of the search and space each time it examines one array element.
Algorithm of BINARY SEARCH
s_key It is the key which search by the user.
size It represents the size of table.
array it is the temporary variable which stores the value of element.
FUNCTION BINARY_SEARCH (s_key, array, size)
(1) [SET AND READ THE VALUE OF current AND size]
Read size
18 Royal Education-SYBCA Material
ALGORITHAM OF LINEAR
SEARCHING
Royal Education Preparation without Parents Blessing is Stack without Top
(2) [READ THE ELEMENTS FOR THE TABLE IN THE ARRAY]
Repeat for (current = 0 to current < size)
Read array (current)
(3) [READ THE ELEMENT WHICH WE WANT TO SEARCH IN
THE TABLE (s_key)]
Read s_key
(4) [INITIALISE THE VALUE OF low AND high]
low = 1
high = size
(5) [SEARCH FOR THE ELEMENT IN THE ARRAY]
Repeat while (low <= high)
Then
mid = ( low + high) / 2
If (array [mid] = s_key)
Then
Write (s_key, mid + 1)
Else
If (s_key > array [mid])
Then
Low = mid + 1
Else
High = mid - 1
(6) [FINISHED] Return
Algorithm of LINEAR SEARCH
s_key It is the the key which search by the user.
size It represents the size of table.
array it is the temporary variable which stores the value of element.
FUNCTION LINEAR_SEARCH (s_key, array, size)
(1) [READ THE SIZE OF THE TABLE]
Read size
(2) [READ THE ELEMENTS FOR THE TABLE IN THE
ARRAY]
Repeat for (current = 0 to current < size)
Read array (current)
(3) [READ THE ELEMENTS WHICH WE WANT TO
SEARCH IN
19 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
THE TABLE]
Read s_key
(4) [SEARCH FOR THE ELEMENT IN THE TABLE]
Repeat for (current = 0 to current < size)
If (array [current] = s_key)
Then
Write (array (current))
(5) [FINISHED] Return
STACK
Q.1 State the applications of stack.
Recursion is a main application of stack. E.g. main function,
factorial
Conversion of an infix expression into object code(Evaluation of
expression)
Parenthesis matching
Tower of Hanoi
Circuit Switching
1) Convert the following infix expressions to postfix.
i. (a+b)/(c-d)
= ab+ / cd-
= ab+cd-\
Q.2 what is stack? Explain all operations on stack with
algorithm.
Or
Write an algorithm for PUSH and POP operation of stack.
Or
Formulate algorithms for PUSH and CHANGE operations on stack.
Stack is a data structure in which elements are added and
removed from one end, Last in First out (LIFO), structures. In this list
(linear data structure) insertion and deletions are made at one end,
called the top of stack.
Operation on stack:
Push : Insertion
Pop : Deletion
Peep : Extract information
Update : update information at some specific location
Most accessible element : top
20 Royal Education-SYBCA Material
PUSH
POP
Royal Education Preparation without Parents Blessing is Stack without Top
Least accessible element : bottom
The element can be only be removed in the opposite order form
that in which they were added to the stack. So, it is referred to as
LIFO list.

Stack operations:
The stack as an Abstract Data Type (ADT), the operations that
add an element to the top of the stack is usually called PUSH
operations. The operation that takes the top element from the top of
stack is called POP operation.
Implementation of Stack:
A stack is a list, and list can be implemented by two ways:
Array (static implementation)
Pointer (linked list/ dynamic implementation)
s It is the array having the of n element
top It is the pointer which will points to top of the stack.
x It is the variable which will store the value / item that we want to
or from push or pop on stack.
FUNCTION PUSH (s, top, x)
(1) [CHECK FOR STACK OVER-FLOW]
If top=size-1
Then
Write (STACK IS OVER FLOW)
Return
(2) [INCREAMENT top POINTER]
top = top + 1
(3) [INSERT ELEMENT AT top OF STACK]
s[top] = x
(4) [FINISHED]
Return
FUNCTION pop (s, top, x)
(1) [CHECK FOR UNDER FLOW]
If top < 1
Then
Write (STACK IS UNDER FLOW)
Return
(2) [ASSIGN THE TOP VALUE OF ARRAY s TO x]
x = s[top]
(3) [DECREAMENT top POINTER]
21 Royal Education-SYBCA Material
PEEP
CHANGE
Royal Education Preparation without Parents Blessing is Stack without Top
top = top 1
(4) [PRINT THE POPPED ELEMENT]
Write (x)
(5) [FINISHED] Return
Algorithm: PEEP (S,Top,i)
Step 1 : [check for stack under flow]
If (TOP i +1) <= 0
Then write (stack under flow)
Exit
Step 2 : [return the ith element from the top of stack]
X <- S(TOP i+1)
Step 3 : [Finished]
Exit
Algorithm: Change (S,TOP,X,i)
Step 1 : [check for stack under flow]
If (TOP i +1) < 0
Then write (stack under flow)
Exit
Step 2 : [change the element value from top of stack]
S[TOP i + 1] <- X
Step 3 : [finished]
Exit
Q.3 What are the advantages and disadvantages of link list
over array?
Advantages
A link list is a dynamic data structure i.e. memory is allocated
at run time.
Link list can grow or shrink in size during the execution of a
program so memory is less wasted.
It can have more than one data types.
It is easier to delete or insert items by rearranging the links.
Disadvantages
A link list will use more storage than an array with the same
number of items.
Whenever we deal with a fixed length list, it would be better to use
an array rather than a link list.
22 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Q.4 Explain any two suitable examples of stack.
Two examples of stack are recursion and Machine level and
hardware level processing
Q.5 Define stack. What do u mean by Underflow and Overflow
conditions?
It is a type of linear list in which insertion and deletion of an
element takes place at one end.
Underflow-: When the stack is empty and we try to pop a value from
the stack the condition is know as stack underflow.
Overflow-: When the stack is full and we try to push and element in
the stack the condition is known as stack overflow condition
Q.6 Explain any two suitable example of stack.
Ans. Elevator (lift) is the one of the best example of
implementation of stack.
Another example is, consider a stack of plates on the counter in
cafeteria,
during the time of dinner, customers take plates from the top of the
stack and waiter puts the washed plates on the top of the stack. So
new plates are put on the top and old one is yet bottom.
Most micro-processor (like one in your computer) use a stack based
Architecture. When a member function is called, it return address and
arguments pushed into a stack, and when function returns they are popped off,
the stack operations are built into the micro-processor.
Q.7 What is data structure?
Data may be organized in many different ways, the logical or
mathematical model of a particular organization is called data
structure.
Q.8 Explain PEEP and CHANGE operation of stack.
Ans. In peep operation, we can display the data (element value) of a
specific element; if stack has some elements. In this operation, we
simply move the pointer to the desired location and then fetch the
information associated with that location.
Peep
Peep: This procedure (function) find the information (elements value)
X at the ith element from the top of the stack, which is represented
by a vectors containing N elements with top pointer Top.
Algorithm: PEEP (S,Top,i)
Step 1 : [check for stack under flow]
If (TOP i +1) <= 0
Then write (stack under flow)
Exit
Step 2 : [return the ith element from the top of stack]
23 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
X <- S(TOP i+1)
Step 3 : [Finished]
Exit
Change : using change operation, user can change the contents of the
ith element (specific location) value from the top of the stack.
Suppose user wants to update information at the i
th
location in the
stack S. to move top pointer to the ith location from the top of the
stack and input the new value of that location.
Change
Algorithm : Change (S,TOP,X,i)
Step 1 : [check for stack under flow]
If (TOP i +1) < 0
Then write (stack under flow)
Exit
Step 2 : [change the element value from top of stack]
S[TOP i + 1] <- X
Step 3 : [finished]
Exit
5>convert the following infix expressions into postfix
a) a + b * c-d / f + g
b) a +b ^ c /d - f
10> infix expression into prefix
a>((( p * q ) * r ) s ) / t
( (*pq * r)-s)/t
( **pqr s)/t
-**pqrs /t
/-**pqrst
b> a + b * c / d - e$f$g
a + b * c / d - e$ $fg
a + b * c / d - $e $fg
a + *b c / d - $e $fg
a + /*b c d - $e $fg
+a / *b c d - $e $fg
-+a /*b c d $e $fg
Q.9 convert expressions to reverse to reverse polish notation
(postfix):
(a) a + b * c d
a+bc* -d
abc*+ -d
abc*+d-
(b) (a + b) / (c d)
24 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
ab+ / cd-
ab+cd-/
c) a * b / c +d
ab* /c+d
ab*c/ + d
ab*c/d+
d) ( a + b) * c d e
oab+ * c - de
oab+ c* de-
Q.10 Convert the following infix expressions into postfix.
a>a + b * c d / f + g
a+ bc* - d/f+g
a+ bc* - df/ +g
a+ bc* - df/ +g
abc*+ - df/ + g
abc*+df/- + g
abc*+df/- g+
b> a * b ^ c / d f
a* bc ^ /d-f
abc^* /d-f
abc^*d/ - f
abc^*d/ f-
Q.11 convert the expression
(A - (B / C))
Read Symbol Stack Output
1 (
2 ( A
3 (- A
4 (-( A
5 (-( AB
6 (-(/ AB
7 (-(/ ABC
8 (- ABC/
9 ABC/-
to postfix expression by showing the status of stack as well as output
when every character is scanned from left to right.
Q.11 Show tracing of converting following expression from
infix to postfix using stack:
( ( a + b ) / ( d * e ) )
Read Symbol Stack Output
1 (
2 ((
25 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
3 (( a
4 ((+ a
5 ((+ ab
6 ( ab+
7 (/ ab+
8 (/( ab+
9 (/( ab+d
10 (/(* ab+d
11 (/(* ab+de
12 (/ ab+de*
13 ab+de*/
Convert the expression
((A-(B/C)) ^ D) / (E -F) to postfix expression by showing the
status of stack as well as output when every character is
scanned from left to right.
Q.12 Algorithm of Infix to Postfix.
1) Examine the element in the input.
2) If it is an operand output.
3) If it is an opening parenthesis push it in the stack.
4) If it is an operator than
I. If stack is empty than push the operator in the stack.
II. If the top of the stack is an opening parenthesis, push
the operator in the stack.
III. If it has a higher priority than the top of the stack push
the operator in the stack.[Except for exponent]
IV. Else pop the operator from the stack and output it,
repeat step 4
5) If it is a closing parenthesis pop operator from the stack and
output then or if it is an opening parenthesis until an opening
parenthesis pop and discard the parenthesis.
6) If there is more input go to step 1.
7) If there is no more input unstuck the remaining operators to
output.
8) Algorithm for balancing Symbol.
1. Make empty stack, read characters until the end of file.
2. If the characters in opening symbol push it on the stack.
3. If it is closing symbol if the stack is empty report an
error.
Else
Pop the stack.
4. If the symbol popped is not corresponding opening
symbol report error.
5. At the end the stack is not empty report error.
Q.13 Algorithm of Infix to Prefix.
1. Reverse the input string.
2. Examine the next element in the input.
26 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
3. If it is an operand add it to output string.
4. It is closing parenthesis push on to stack.
5. If it is an operator than
If stack is empty push operator on stack.
If top of stack is closing parenthesis than push operator on
stack.
If it has higher priority than the top of stack push operator on
stack.
Else pop the operator from the stack and edit it continue
repeat step.
6. If it is an opening parenthesis pop operator from the stack
and add them to output string until a closing a parenthesis is
encounter pop and discard the closing parenthesis.
7. If there is more input go to step 2.
8. If there is no more input unstuck the remaining operator and
add them to output string.
9. Reverse the output string.
Q.14 Algorithm of postfix evolution.
1) When a number is seen it is push on to the stack.
2) When an operator is seen the operator is applying the 2
numbers that are pop from the stack. The result is push back on to
the stack.
3) Repeat the first 2 steps until you have the input.
QUEUE
Q.1 What does FCFS stands for? Differentiate between stack
and queue
FCFs stand for First Come First Serve Basis. It is the
implementation of queue wherein the customer coming first
is server first.
Stack Queue
Stack implements LIFO
(Last in First
Queue implements FIFO
(First in First Out)
27 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Out)mechanisms mechanism
Stack maintains a top
pointer
Queue maintains tow
pointers named Front and
Rear
When item is added to the
stack the operation is
called push and when item
is removed from the stack
the operation is called
pop.
Insertion are done at one
end called rear and
deletion are done at the
other end called front of
queue
Example of stack
Evaluating postfix
expression
Converting infix to
postfix
Example of queue
In CPU ,scheduler
keeps all the current
processes in a queue with
the active process in front
of the queue
Draw the diagram of stack Draw the diagram of queue
Q.2 Explain application of queue in CPU scheduling
In multitasking operating system, CPU is shared between multiple
processes. At given time, only one process is running, all other are
sleeping. The CPU time is administered by the scheduler. The
scheduler keeps all current processes in a queue with the active
process at the front of the queue.
Q.3 What is queue?
Queue is a linear data structure in which insertions are done at the
one end called rear and deletions are done at other end called front.
Hence Queue is called FIFO list.
- Give the definition of
1) Priority Queue A queue in which we are able to
insert items or remove items from any position based on some
priority is often referred as a priority queue.(2004)
2) Deque It is a linear list in which insertions and
deletions are made to or from either end of the structure.(2004)
Q.4 Different types of Queue are as follows
Circular queue-: In case of circular queue, the last element
point back to the first element of the queue. So no NULL pointers
are required
Eg-: used in process scheduling by operating system.
28 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Priority Queue-: A queue in which we are able to insert items
or remove items from any position based on some priority is
often referred as a priority queue.
Eg-: Time sharing System
Deque-: It is a linear list in which insertions and deletions are
made to or from either end of the structure.
Two type of Deque
oAn Input restricted deque
oAn output restricted deque
Advantages-:
Queue mechanism is used in CPU scheduling
It is used in Time sharing System
Disadvantages-:
There is possibility that the queue is reported as full(When rear
reaches the end of the array)even though there might be empty
slots at the beginning of the queue.
Q.5 Explain priority queue.
o A queue in which the elements are inserted or removed on
some priority basis is known as priority queue.
o A queue in which we are able to insert or remove items from
any position based on some property is often referred as priority
queue.
o Priority queue means user have to give some priority to a node
in terms of insertion or removal of the elements.
P
1
P
2

.
P
i-
1
T
1
T
2
.
.
T
j-
1
S
1
S
2
. S
k-
1
.
.
1 1
.
1 2 2 .
.
2 3 3 .
.
3 .
.
o A priority queue can be represented in memory using two ways.
- Using a single one-dimensional array.
- Using a one-way linked list.
o Normally the priority queue is represented using
separate one- dimensional queues. Each follows FIFO
behaviour.
ADVANTAGE:
They are useful scheduling of jobs seeking the CPU. All the jobs
needing CPU forms a CPU queue, which is generally known as ready
queue.
29 Royal Education-SYBCA Material
Pi
Tj
S
k
Royal Education Preparation without Parents Blessing is Stack without Top
Q.6 Take types of queue.
I. Simple Queue
II. Circular Queue
III. Dqueu
IV. Priority Queue
Q.7 Why circular queue is more suitable than simple queue?
+ Algorithm of simple queue is wasteful in terms of storage if the
front pointer F never manages to catch up to the rear pointer.
+ An arbitrary large amount of memory would be required to
accommodate the elements.
+ These methods of performing operations on a queue should be
only useful when the queue is emptied at certain intervals.
+ A more suitable method of representing a queue which
prevents an excessive use of memory is to arrange the elements
Q[1],Q[2],.Q[N] in a circular fashion.
+ In other words in a simple queue we face the problem of queue
overflow frequently.
Here it may happen that a simple queue contains only one element
at N
th
position. All other locations (from 1to N-1) are empty, but still
we get overflow because of (R=N). If some how, we are able to
utilize the previous (N-1) locations, then overflow will only occur if
queue contain total N elements and you will try to insert more
elements and you will try to insert more elements.
+ The above problem can be solved if we treat a simple queue as
a circular queue. i.e. The elements of the queue are arranged in a
circular queue is referred as circular queue.
Q.8 Application of queue.
There are several algorithms that use queues to
solve problems efficiently.
When the jobs are submitted to a networked
printer, they are arranged in order of arrival. Thus; essentially,
jobs sent to a printer are placed on a queue.
Virtually, every real-life lines a queue.
e.g.:-lines at ticket counters at cinema halls, railway station, bus
stands, etc. in all these e.g. are on first come first serve basis.
Q.9 Explain circular queues operations threw algorithm.
After reaching at last position of the array, the rear moves
towards the first position of the array, only when there is a vacant
place at the beginning of the array.
+ In Circular queue, the value of rear is incremented
If (rear ==size-1)
Rear=0;
Else
Rear++;
30 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
+ Similarly the value of front is incremented as:
If (front ==size-1)
front=0;
Else
front++;
TAKE THE PRINT OUTS ON PG:153,154,155
Q.10 Explain Deque, its structure, its operation with algorithm.
A deque (Double ended queue) is a linear list in which insertion and
deletions are made at both ends but not in the middle.
Representation of a deque
A deque is more general then stack or queue.
There are two variations of a deque.
An input restricted and an output restricted deque.
The input-restricted deque allows insertion at only one end(i.e. at
rear) and deletions occur at both ends.
The output restricted deque allows deletions at only one end(i.e. at
front) and insertions occur at both ends.
There are two types deque.
1) IRD:
In this type of the deque insertion of new element is restricted to only
one end of the list (rear end).But removal of elements can be take
place at both ends.
2) ORD:
In this type of deque removal of the element is restricted to only one
end (front).But insertions of new elements can be take place at both
ends.
Algorithm:
>> Insertion from right end in a deque
DQ:-deque
N:-elements which is maintained by array
F:-front
R:-rear
ITEM:-It is new data to be inserted
RDQInsert (DQ, F, R, N, ITEM)
Step 1. [Overflow?]
31 Royal Education-SYBCA Material
Deletion
Insertion
Front
Rear
Deletion
Insertion
Royal Education Preparation without Parents Blessing is Stack without Top
If (F==1 and R==N) OR (F==R+1)
Then
Write (OVERFLOW)
Return
Step 2. If(F==0)
Then
F=R=1
Else if(R==N-1)
Then
R=1
Else
R=R-1
Step 3. DQ[R]=ITEM
Step 4. Return
>> Insertion from left end in a deque
DQ:-deque
N:-elements which is maintained by array
F:-front
R:-rear
ITEM:-It is new data to be inserted
LDQInsert (DQ, F, R, N, ITEM)
Step 1. [Overflow?]
If (F==1 and R==N) OR (F==R+1)
Then
Write (OVERFLOW)
Return
Step 2. If(F==0)
Then
F=F-1
If (F==0)
Then
F=N
Step 3. DQ[F]=ITEM
Step 4. Return
>> Deletion from right end in a deque
DQ:-deque
N:-elements which is maintained by array
F:-front
R:-rear
ITEM:-It is a variable which is stored a deleted item.
RDQDeletion (DQ, F, R, N, ITEM)
Step 1. [Underflow?]
If (F==0)
Then
Write (UNDERFLOW)
32 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Return
Step 2. ITEM=DQ[R]
Step 3. If (F==R)
Then
F=R=0
Return
Else
R=R-1
If(R=0)
Then
R=N
Step 4. Return
>> Deletion from left end in a deque
DQ:-deque
N:-elements which is maintained by array
F:-front
R:-rear
ITEM:-It is a variable which is stored a deleted item.
LDQDeletion (DQ, F, R, N, ITEM)
Step 1. [Underflow?]
If (F==0)
Then
Write (UNDERFLOW)
Return
Step 2. ITEM=DQ[F]
Step 3. If (F==R)
Then
F=R=0
Else If (F=N+1)
Then
F=1
Else
F=F-1
Step 4. Return
Simulation
One of the areas to which queues can be applied is that of
simulation. Simulation is the process of forming a theoretical
model from a real situation in order to understand the impact
of modifications and effect of introducing various strategies on
the situation.
A simulation program attempts to model a real world
situation in order to learn something about it as it would be
too expensive or dangerous to experiment with the real
system. Areas such as military operations are safer to
simulate than to field-test.
33 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Large number of different situation may be included in a
simulation and their results can be compared. If program
successfully represents real world situation, the results of the
program would also be reflected.
Any process or situation we wish to simulate is considered a
system. A System is a group of objects interacting in order to
produce some result. A Continuous System has parameters
which can take any real value in some given interval.
Discrete Systems have parameters which can only take
values from a fixed number of choices.
In order to simulate a system a model of the system must
be produce & to determine the structure of a model for some
situation, the entities, attributes & activities of the system
should be determine.
An entity represents the components of the system & is the
object that is persons, places or things of interest in the
simulations.
Attributes denote the characteristics of these entities. The
state of the system at any given time is specified by the
attributes of the system entities and the related among the
entities at that time.
An activity is a process that causes a change of system
state & event is the occurrences of an activity at a particular
instant of time.
If we consider a bank system an example entities should be
customer. The attribute for the customer could be the balance
in the account. The activity might include deposits or
withdrawals. An event would occur when a customer enters or
leave the queue.
LINKED LIST
34 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Below are the algorithm mentioned for all linked list please
refer to most important questions which are mentioned
below.
Write an algorithm to append an element to the end of
doubly link list and delete the last element from the link list
Write an algorithm to delete all occurrences of a given
element in singly linked list
Write an algorithm to insert a node in the single link list
in ascending order
Create an algorithm to merge two single link list into
first(page 47 Summanta)
Algorithm to insert an element in a doubly linked list
Algorithm to delete an element in a doubly linked list
Write a short note on circular link list
Link List
ADVANTAGE OF CIRCULAR LINKED LIST: -
In circular linked list the last node points to the first node so there
is no any node which link portion is null. The advantage of circular
linked list is that suppose we are on the second last node of the
linked list and then we want to traverse to first node than we can
reach to first node second last node to last node and from last node
to first node while in singly linked list it is not possible because last
node points to null.
Q. What is linked list.Explain each type of linked list with its
structure.
A linked list is a linear collection of data elements, called nodes.The
linear order is given by pointers.
1. Singly linked list
2. Doubly linked list
3. Circular Singly linked list
4. Circular Doubly linked list
5. Polynomial linked list
Singly Linked List:-
In this linked lists each nodes are divided into two parts and it had one
way node structure.
3 2 4 10
Struct singly
{
Int data;
Struct singly*next;
}*head==NULL;
35 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Doubly Linked List:-
In this linked lists each nodes are divided into three parts and it had
two way node structures.
3 3 7 2 14 1 10 0
Struct doubly
{
Int data;
Struct doubly*next;
Struct doubly*prev;
}*head==NULL;
Circular Singly Linked List:-
In this one way circulation can happen and each node has one
pointer but it is circular otherwise it is quite similar with singly linked
list.
3 2 1 10
Struct singly
{
Int data;
Struct singly*next;
}*head==NULL;
Circular Doubly Linked List:-
In this one way circulation can happen and each node has one
pointer but it is circular otherwise it is quite similar with singly linked
list.
3 3 7 2 14 1 10 0
Struct doubly
{
Int data;
Struct doubly*next;
Struct doubly*prev;
}*head==NULL;
Polynomial is an important application of linked list is to
accommodate a number of polynomials of growing sizes so that their
combined size does not exceed the total memory available.
36 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
COEFF EXP LINK
Structure of polynomial
Struct poly
{
Int coeff;
Int exp;
Struct poly*next;
}
e.g.: p(x)=3x
2
-7x
2
+14x+10
3 3 7 2 14 1 10 0
Q. Application of linked list
To implement other data structures such as stacks, queues, trees and
graphs.
To manipulate polynomials.
To represent sparse matrices.
To implement polynomial manipulation
37 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
TREE
Q.1 State the rules of converting a general tree into binary
tree also convert the given general tree in binary tree.
Ans. A general tree can have any number of nodes. The children of a
node are called Siblings of each other.
To represent the general tree as binary trees, two pointers are
maintained. One pointer points to first child of a node and other
pointer points to the siblings of the node. The structure of the nodes
can be defined as follows:
Struct general
{
int data;
struct general*first child;
struct general*siblings;
};
The in-memory view of a node of the tree is shown in figure:
General

data first sibling
child
While representing a general tree as a binary tree, the pointer to
the first child of a particular node is made the left of that node and
the right child is pointer to the siblings of the node.
Thus while representing a general tree any node has only two
children. Hence, a general tree can be represented as a binary tree.
Q.2 Define binary tree and expression tree.
Ans A binary tree T is a finite set of nodes, such that
(a) T is empty (called empty binary tree) or
(b) T contains a specially designated nodes of T, and remaining
nodes of T form two disjoint binary trees T1 and T2 which are
called left sub-tree and right sub-tree respectively.
or
Binary Tree: -
If in a directed tree the outdegree of every node is less than or equal to
2 than the tree is called Binary Tree.
38 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Sample Binary Tree
Q.3 Difference between Tree and Binary Tree.
Ans.
Tree Binary Tree
A Tree can never be Empty A Binary tree may be empty
A Tree a node may have any
number of Children.
A Binary Tree a node may have
at most two children.
Q.4 Define Expression Tree.
Ans. An Expression tree is a binary tree which stores an arithmetic
expression.
The leaves of an expression tree are operands. Expression tree is
always a
Binary tree because an arithmetic expression contains either
binary
Operator or unary operator (hence a internal nodes has at most
two
Children) following figure show an expression tree for me
arithmetic
Expression.
(A+B*C)- ((D*E+F)/G)
TREE TRAVERSAL OPERATION: -
Traversal operation is that operation by which each node in the tree
is processed exactly one in a systematic manner.
There are three main ways of traversing a binary tree:
1. Preorder Traversal: -
In preorder traversal each node is processed in following manner:
I. Process the root node.
II. Traverse the left subtree in preorder.
III. Traverse the right subtree in preorder.
2. Inorder Traversal: -
The inorder traversal of a binary tree is given by the following
manner:
I. Traverse the left subtree in inorder.
II. Process the root node.
III. Traverse the right subtree in inorder.
3. Postorder Traversal: -
The Postorder Traversal of a binary tree as follow:
I. Traverse the left subtree in postorder.
II. Traverse the right subtree in postorder
III. Process the root node.
39 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Q.5 Write the applications of Tree.
Ans. The presentation contains three applications of trees. The first
describes methods for the mechanical manipulation of arithmetic
expressions.
An interesting application of trees concerning the construction
and
Maintenance of symbol tables.
The tree also plays an important role n the areas of syntax analysis,
where it is used to display the structure of Sentence in a language
and is used in defining unambiguous languages.
Q.6 Advantages & Disadvantages of Threaded Binary Tree.
Ans.
Advantages:
The traversal operation is faster than that of its unthreaded
version, because with threaded binary tree non-recursive
implementation is possible which can run faster and does not
require the botheration stack management.
The second advantage is more suitable with a threaded binary
tree; we can efficiently determine the predecessor and successor
nodes starting from any node. In case of unthreaded binary tree,
however, this task is more time consuming and difficult. For this
case, a stack is required to provide upward pointing information in
the tree whereas in a threaded binary tree, without having to incur
the overhead of using a stack mechanism the same can be carried
out with the threads.
Any node can be accessible from any other node. Threads are
usually more to upward whereas links are downward. Thus in a
threaded tree, one can move in either direction and nodes are in
fact circularly linked. This is not possible in unthreaded counter
part because there we can move only in down ward direction
starting from root.
Insertions into and deletions from a threaded tree are although
time consuming operations (since we have to manipulate both
links and threads) but these are very easy to implement.
Q.7 Enlist types of tree. Explain any two of them with diagram.
Ans. Types of binary trees.
There are several types of binary tree possible each with its own
properties. Few important & frequently used trees are as below:
1) Expression Tree.
2) Binary Tree.
3) Heap Tree.
4) Threaded Binary Tree.
5) Huffman Tree.
6) Height Balanced Tree(also know an AVL Tree)
7) Decision Tree.
40 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Binary Search Tree:
A binary tree T is termed as binary search tree (or binary sorted
tree) if each node N of T satisfies the following property:
The value at N is greater than every value in the left sub-tree of N
and is less than every value in the right Sub-tree of N. figure shows
two binary search trees for two different types of data.
Q.8 Write an algorithm to delete a node from ordered binary
tree.
Ans. Case 1; N is the leave node
Case 2: N has exactly one child
Case 3: N has two children.
Algorithm BST_DELETE (ITEM)
Input: ITEM is the data of the node to be deleted.
Output: if the node with data as ITEM exist it is deleted else a
message.
Data Structure: Linked structure of binary tree. Pointer to the root
node is ROOT.
Steps:
1. ptr = ROOT, flag = FALSE
2.while (ptr != NULL) and (flag = FALSE) do // step to find the
location of the node
1. case : ITEM < ptr.DATA
1. parent =ptr
2. ptr = ptr.LCHILD
2. case: ITEM > ptr.DATA
1. parent = ptr
2. ptr = ptr.RCHILD
3. case: ptr.DATA = ITEM
1. flag = TRUE
4. End Case
3. End While
4. If (flag = FALSE) then //when node does not exist
1. Print Item does not exist: No deletion
2. Exit. // Quit the execution.
5. End if
/* DECIDE THE CASE OF DELETION */
1 if (ptr.LCHILD =NULL) and (ptr.RCHILD = NULL) then
// node has no child
1. case =1
2 Else
1. if (ptr.LCHILD != NULL) and (ptr.RCHILD !=) then
// node contains both child.
41 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
1. case = 3
2. else
1. case = 2 // node contains only one
child
3. End if
3. End if
/* DELETION: CASE 1 */
1 if (case = 1) then
1. If (parent. CHILD = ptr) then // if the node is a left child
1. parent. CHILD = NULL // set pointer of its parent
2. Else
1. parent. CHILD = NULL
3. End IF
4. Return NODE (ptr) // return deleted node to the memory
bank
5. EndIf
/* DELETION: CASE2 */
11. if(case = 2) then
1. if (parent.LCHILD = ptr) then
1. If (ptr.LCHILD = NULL) then
1. Parent.LCHILD = ptr.RCHILD
2. Else
1. Parent.LCHILD = ptr.LCHILD
3. End If
2. Else
1. If (parent.RCHILD = ptr) then
1. If (ptr.LCHILD = NULL) then
1. Parent.RCHILD = ptr.RCHILD
2. Else
1. Parent.RCHILD = ptr.LCHILD
3. End if
2. End if
3. EndIf
4. RETURN_NODE (ptr)
12. End IF
13. If (case = 3)
1. ptr1 = SUCC(ptr)
2. item1 = ptr1.DATA
3. BST_DELETE (item1)
4. ptr.DATA = ITEM
14. EndIf
15. Stop
Q.9 Define AVL Tree.
42 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
Ans. An AVL tree is a binary tree in which the left and right sub trees of
any Node may differ in height by at most 1, and in which both the sub
trees are Them selves AVL Tree.
Q.10 Define B Tree.
Ans. B-tree is a multi-way search tree of order n that satisfies the
following
Conditions:
(a) All the non-leaf nodes (expect the root node) have at least n/2
children and at the most n children.
(b) The non-leaf root node may have at the most n non-empty child
and at least two child nodes.
(c) A B-tree can exist with only one node i.e. the root node
containing no child.
(d) If a node has n children then it must have n-1 values. All the
values of a particular node are in increasing order.
(e) All the values that appear on the left most child of a node are
smaller than the first value of that node. All the values that appear
on the right most child of a node are greater than the last value of
that node.
(f) If x and y are any two i
th
and (i+1)
th
values of a node, where x
<y, then all the values appearing on the (i+1)
th
sub-tree of that
node are greater than x and less than y.
(g) All the leaf nodes should appear on the same level.
Q.11 Write recursive algorithms for pre order and post order
traversals.
Ans Algorithm PREORDER (ROOT)
Input: ROOT is the pointer to the root node of the binary tree.
Output: Visiting of all the nodes in preorder fashion.
Data Structure: Linked structure of binary tree.
Steps:
1. ptr = ROOT //start from the ROOT
2. If (ptr! = NULL) then //if it is not an empty node
1. VISIT (ptr) //visit the node
2. PREORDER(ptr.LC) //traverse the left sub-tree of the
node in preorder
3. PREORDER(ptr.RC) //traverse the right sub-tree of
the the node in preorder
3. EndIf
4. Stop
Algorithm POSTORDER (ROOT)

Input: ROOT is the pointer to the root node of the binary tree.
Output: Visiting of all the nodes in preorder fashion.
Data structure: Linked structure of binary tree.
Steps:
43 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top
1. ptr = ROOT //Start from the root.
2. If (ptr! = NULL) then //if it is not an empty node.
1. POSTORDER (ptr.LC)
//Traverse the left sub-tree of the node in inorder.
2. POSTORDER(ptr.RC)
//Traverse the right sub-tree of the node in
inorder.
3. VISIT (ptr) //visit the node.
3. EndIf
4. Stop
Q.12 Write non- recursive algorithms for pre order and post
order traversals.
Algorithm pre-order_stack (root)
Input: a binary tree represented with three parallel arrays, root node is
being identified by the root.
Output: visiting all the nodes in the tree in preorder fashion.
Data Structure: a Stack info and three parallel arrays representation of
Binary tree.
Steps:
1. PUSH (ROOT) // push the root nodes location
into the stack INFO.
2. While (TOP! =0) do //till the stack is not empty
do
1. ptr = POP() //get the top element in the stack
2. If (ptr! = NULL) then
1. VISIT (DATA [ptr]) //to visit the current node
2. PUSH (RCHILD [ptr]) //next left child of the current
node will be visited.
3. PUSH (LCHILD [ptr])
3. EndIf
3. End While
4. Stop
Algorithm IN-ORDER_STACK (ROOT)
Input: A binary tree represented with tree parallel arrays, root node is
Being identified by ROOT.
Output: Visiting all the nodes in the tree in inorder fashion.
Data Structure: A stack INFO and three parallel arrays representation
of binary tree.
Steps:
1. ptr = ROOT
2. While (TOP! = 0) or (ptr! = NULL) do
1. If (ptr! = NULL) then
1. PUSH (ptr)
2. ptr = LCHILD [ptr]
44 Royal Education-SYBCA Material
33
Royal Education Preparation without Parents Blessing is Stack without Top
2. Else
1. ptr = POP( )
2. VISIT (DATA [ptr])
3. ptr = RCHILD [ptr]
3. EndIf
3. End While
4. Stop
Q.13 what is binary search tree?
A binary tree T is termed as binary search tree(or binary sorted
tree) if each node N of satisfies the following property
The value of N is greater than every value in the left sub tree of N
and is less than every value in the right sub-tree of N.
Explain following terms.
Height of tree-: Maximum number of nodes that is possible in a path
starting from root node to a leaf node is called the height of a tree.
Degree of a tree-: Maximum number of children that is possible for a
node is called the degree of the tree
Full binary tree-: A binary is a full binary tree if it contains maximum
possible number of nodes in all levels
Complete binary tree is said to be complete if all its levels accepts
the possibly last level have the maximum number of possible nodes
and all the nodes at the last level appear as far as possible.
Forest-: Forest is defined as collection of disjoint tree as shown in the
figure below
If we delete root node and all its branches connected with
nodes at level 1 then we get a set of disjoint trees .The set of disjoint
trees is called a forest.
Ordered Tree: -If in a directed tree an ordering of the nodes at
each level is given than such a tree is called an Ordered Tree.
Complete m-ary Tree OR Full m-ary Tree: -
In a directed tree if the outdegree of every node is exactly equal to m
or 0 than the tree is called a Complete or Full m-ary Tree.
Level of Tree: -
The level of any node is the length of its path from the root.
m-ary Tree: -
If in a directed tree the outdegree of every node is less than or equal to
m then the tree is called an m-ary tree.
45 Royal Education-SYBCA Material
33
Royal Education Preparation without Parents Blessing is Stack without Top
Q.14 What is AVL tree? Discuss its four cases of rotation.
AVL Tree
Def: A binary search tree is said to be height balanced binary search
tree if all its nodes have a balanced factor of 1, 0, and -1 that is,
|bf| = |h
L
- h
R
| <= 1,
For every node in the tree.
(a) Height balanced (b) height
unbalanced
AVL Rotations
In order to balance a tree, one elegant method devised in 1962 by
two Russian mathematicians, G.M.Adelson-Velskii and E.M. Lendis,
and the method is named as AVL rotation in their honour.
There are four cases of rotations possible which is discussed as
below:
Case 1: unbalance occurred due to the insertion in the left sub-tree of
the left child of the pivot node.
right sub-tree (A
R
) of left child (A) of pivot node (P) becomes
the left sub-tree of P.
P becomes the right child of A
Left sub-tree (A
L
) of A remains the same
46 Royal Education-SYBCA Material
6
8 2
1 4
33
7
7
1
-1
0
0
1 0
1
2
-1
0
0
0
0
0
6
8 2
1 4
3
6

6
1
Royal Education Preparation without Parents Blessing is Stack without Top
This case is called Left-to-Left insertion.
(a) a height balanced tree as |bf| <= 1
2
C
47 Royal Education-SYBCA Material
8
1
6
4 7
3
9
1
0
0
0
0
1
5
11
0
0
0
8
10 6
4 7
3
9
2
1
1
0
0
2
5
11
0
0
0
2
0
Royal Education Preparation without Parents Blessing is Stack without Top
(b) after the insertion of 2 into the tree
P

A
(c) AVL rotation as per the left-to-left
(Case 1) insertion
48 Royal Education-SYBCA Material
A
L
A
R
8
10
6
4 7
3
6
9
2
1
1
0
0
2
5
11
0
0
2
0
8
1 6
4 7
3
6
9
5
11
2
8
10 4
2
9 11
P
R
Royal Education Preparation without Parents Blessing is Stack without Top

A
L
A
R
P
R
(d) After AVL rotation
0
1 0 0
0
0 0
0
(e) Height balanced tree with newly inserted node
2 and after avl rotation
Case 2:
Unbalanced occurred due to the insertion in the right sub-tree of the
right child of the pivot node. This case is reverse and symmetric to
case 1.
left sub-tree (B
L
) of right child (B) of pivot node(P) becomes
the right sub-
tree of P.
P becomes the left child of B>
Right Sub-tree (B
R
) of B remains same.
This case is know as right-to-right insertion.
49 Royal Education-SYBCA Material
N D N
N
N E N
N
N F N
N
3 6
5
7
8
10
4
3 6
2
9
0
1
5
11
7
Royal Education Preparation without Parents Blessing is Stack without Top
Illustration: case 2 of AVL rotation occurs due to Right-to-Right
insertion.
TAKE THE PRINTS ON PAGE: 283[(a),(b)]
Case 3: unbalance occurred due to the insertion in the right sub-tee of
the left child of the pivot node. The case is know as Left-to-Right
insertion.
Case 3 involves two rotations for the manipulation in pointers:
-> Rotation 1: (1) left sub-tree (B
L
)of the right child(B) of the left child
of the pivot node (P) becomes the right sub-tree of the left
child (A)
(2) left child(A) of the pivot node(P) becomes the left child of B.
-> Rotation 2: (1) right sub-tree (B
R
) of the right child(B) of the left
child (A) of the
Pivot node (P) becomes the left sub-tree of P.
(2) P becomes the right child of B.
TAKE THE PRINTS ON PAGE: 285[(a),(b), (c),(d)]
Case 4: unbalance occurred due to the insertion in the left sub tree of
right child of the pivot node. This case is the reverse and symmetric
to case 3. this case is know as right-to-left insertion.
There are two rotations for the manipulations of pointers in this case,
these are:
Rotation 1:
right sub tree(B
R
) of the left child (B) of the right child (A) of
the pivot node (P) becomes the left sub tree of A.
right child (A) of the pivot node (P) becomes the right child
of B.
Rotation 2:
left sub tree(B
L
) of the right child (B) of the right child (A) of
the pivot node
(P) becomes the right sub tree of P.
50 Royal Education-SYBCA Material
N D N
N
N E N
N
N F N
N
Royal Education Preparation without Parents Blessing is Stack without Top
P becomes the left child of B.
Q.14 How many nodes are possible in binary tree of height h?
2
h
-1
Q.15 Siblings :
The nodes having same parent are called Siblings.
For e.g.
Node B and C are Siblings.
Q.16 explain the following terms:
+ Root Node:
The node in a tree that has no parent is call the root node of a tree.
For e.g.
Node A is root node of a tree.
+ Leaf Node :
The node which is at the end and does not have any child is called the
Leaf node.
Sometime Leaf node is referred as terminal node.
For e.g.
Nodes D, H, L, F, J, and K are leaf nodes.
Skew binary tree-: Binary tree has minimum number of nodes, if eah
level has min number of nodes (min possible node must be 1 at every
level)
Q.17 Give the node structure of linked representations of
binary tree.
Ans.
+ Tree is a data structure in which elements are arranged
in non-linear fashion which requires 2D representation.
+ The figure drawn below shows the tree.
+ In a Link List each node has a link that points to another
node in a tree each node may point to several other nodes as shown
in the figure.
51 Royal Education-SYBCA Material
A
B N C
N D N
N
N E N
N
N F N
N
22
22
11
Royal Education Preparation without Parents Blessing is Stack without Top
+ Trees may have many variation, implementation and
application such as compiler construction, database design, operation
system program etc.
Q.18 What is spanning tree? What minimum spanning tree?
Find out the minimum spanning tree from the following graph
with the help of prims algorithm.
Spanning tree is a sub graph of G, is a tree, and contains
all vertices of G.
A minimum Spanning tree is a spanning tree, but has
weights or lengths associated with the edges, and the total weight of
the tree (the sum of the weight of its edges) is at a minimum.
52 Royal Education-SYBCA Material
V1
V2 V3
V4
V5
V6
V7
4 5
2
2
1
3
9
6
1
7
4
6
- -
- -
1 -
7 4
- 9
-
-
6
6
22
22
11
22
22
11
44
11
Royal Education Preparation without Parents Blessing is Stack without Top

Initial tree Stage 1
Stage 2 Stage 3
53 Royal Education-SYBCA Material
V1
V3 V2
V4
V5 V6
V7
V1
V3 V2
V4
V5 V6
V7
2222
2
V1
V3 V2
V4
V5 V6
V7
2
1
V1
V3 V2
V4
V5 V6
V7
22
22
11
V1
V3 V2
V4
V5 V6
V7
22
22
11
44
11
Royal Education Preparation without Parents Blessing is Stack without Top
STAGE 4 STAGE 5

54 Royal Education-SYBCA Material
V1
V3 V2
V4
V5 V6
V7
2
2
1
4
V1
V3 V2
V4
V5 V6
V7
2
2
1
62
1
4
V1
V3 V2
V4
V5 V6
V7
22
22
11
44
11
Royal Education Preparation without Parents Blessing is Stack without Top
Q.19 Create nomaru tree and do heap sort on following data.
10,5,70,15,12,35,50
BINARY TREE.
HEAP SORT
1.
55 Royal Education-SYBCA Material
10
5 70
15 35 50 12
10
15 70
5 35 50 12
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
2.
3.
By this three step binary tree represented as heap tree.
10. Give the structure of threaded binary tree.
Struct node
{
Int data;
Char thread;
Struct node*left;
Struct node*right;
}
Q.20 Give advantage and disadvantage of linked list representation of
binary tree.
Advantages:
Any node can be accessed from any other node by calculating
the index and this is efficient from execution point of view.
Here, data are stored only without any pointers to their
successor or ancestor which are mentioned implicitly.
Programming languages, where dynamic memory allocation is
not possible (such as BASIC, FORTRAN) array representation is the
array only means to store a tree.
Disadvantages:
Other than full binary trees, majority of the array entries
may be empty.
It allows only static representation. It doesnt have any
way possible to enhance the tree structure if the array size is limited.
Inserting a new node to it or deleting a node from it are
inefficient with this representation because these require
considerable data movement up and down the array which demand
excessive amount of processing time.
56 Royal Education-SYBCA Material
70
15 10
5 35 50 12
70
5 35 10 12
15
50
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
Q.21 Explain linked representation of binary tree.
Linear representation of binary trees has a number of overheads. In
linked representation of binary trees, all these overheads are taken
care of
DATA
Structure of a node in linked representation
Here LC and RC are two link fields to store the address of left child
and right child of a node; DATA is the information content of the
node. With this representation if one knows the address of the root
node then from it any other node can be accessed.
Both two structures tree and linked look almost similar implies that
the linked representation of a binary tree very closely resembles the
logical structure the data involved.
Q.22 Application of heap tree
Sorting
Priority queue implementation
GRAPH
57 Royal Education-SYBCA Material
RC
LC
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
Graph A graph G= (V, E) is a relation or mapping between non-
empty vertices V and non-empty set of edges E.
A graph G consists of non empty set V called
a set of nodes of a graph. These nodes can also be called vertices or
point. A set of E, which is a set of edges of the graph and a mapping
from the set of edges E to a set of pair of elements of V.


n1 n2
n3
n4
n5
These graphs consist of a set of points or vertices
v1, v2, v3, v4 which are connected by lines n1, n2, n3, n4, n5. We
can associate a pair of nodes of a graph to every edge. If an edge N
E is associated with the pair of nodes (u, v), where u, v into v then we
can say that the edge can connects or joins the nodes u and v.

+ Direct Graph :-
In a Graph G=(v, e) an edge which is directed from one node to another is called
directed edge and a graph in which every edge directed is called a directed graph or a
digraph. For example, a city maps showing only the
way streets.
+ Mixed Graph :-
In a Graph if some edges are directed and some edges are indirected
then such a graph is called mixed graph. For example, a city maps
showing both one-way and two-way streets.
58 Royal Education-SYBCA Material
V
4
V
1
V
3
V
2
V
4
V
1
V
3
V
2
V
1
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
+ Undirected Graph :-
In a Graph G= (v, e) when an edge has no specific direction is called an
undirected edge and a graph with every as undirected is called an
undirected graph. For example, A map showing only two-way streets.
+ Complete Graph :-
A directed graph is said to be complete if each vertex vi is adjacent
to every other vertex vj in G.

+ Multi Graph :-
Any Graph which contains parallel edges is called a multi graph.
+ Simple Graph :-
A graph in which there is only one edge between a pair of
nodes is called simple graph.
+ Weighted Graph :-
A graph in which weights are assigning to every edge is called a weighted graph.
A graph of a city street may be assign weight according to traffic density on each street.
59 Royal Education-SYBCA Material
V
5
V
2
V
4
V
3
V
6
V
4
V
1
V
3
V
2
V1 V2
V4 V3
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
Q. What is cut vertex?
If a graph is not biconnected then these vertices whose
removal would disconnect the graph are known as cut vertices are
articulation points.
Q. List the application of graph and explain one of them-:
Following are the application of the graphs
1) Pert and related technique
PERT means Programming Evaluation and Review Technique.
By this technique a project is completed in minimum time and
with minimum resources.
In pert the different activities and events are arranged
sequentially and network is prepared. From the network the
interrelationship between the activities becomes clear. In Pert the
project is divided into different parts, each part is known as activity,
and when an activity is completed the result is known as an event. By
arranging the activities and events in logical order a network is
obtained. This network can be called a PERT diagram or a PERT chart.
The estimates of time for different activities are obtained and from
them the total time for completing the entire project is determined.
Activity: In any project if time or resources are used for any work it is
called an activity. If an activity is shown as ---
4
--> it indicates that the
time of 4 units is required for that activity.
Event: The result of any activity is called an event. Each event is
shown by circle in a PERT diagram.

2) Computer graphics application
3) Topological Sorting
Topological Sorting-: This is explained in the notes written with
pen
Pert-:
Difference between complete and connected graph
+ Null Graph :-
A graph containing only isolated nodes is called a null graph.
For example,
60 Royal Education-SYBCA Material
V1
V3 V2
V4
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
Adjacent Node:-
Any two nodes that are connected by an edge in a graph
are called adjacent nodes. In the above graph v1 and v3 are
adjacent.
+ Loop :-
An edge of a graph, which joins to itself, is called a loop.
OR
An edge that initiates or originates in one node and terminates in a
same node is called a loop.
+ Parallel Edges :-
In a Graph are two or more edges originate at one node and terminate
at a same node than those edges are called parallel edges.
+ Isolated Node :-
In a graph a node which is not adjacent to any other node is called an
isolated node. For example,
+ Path :-
A path is said to traverse through the nodes appearing in a sequence
originating in the initial node of the first edge and ending in a terminal
node of the last edge in a sequence.
61 Royal Education-SYBCA Material
V
3
V
2
V
4
V
1
V
3
V
2
V
4
V
1
V
1
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
+ Length :-
The number of edges appearing in a sequence of a path is called
the length of the path.
+ Cycle :-
For a directed graph a path which originate and ends in a same
node is called a cycle or circuit.
+ Acyclic :-
A simple directed graph, which does not have any cycle is called
acyclic graph.
+ Pendent Vertex :-
A vertex vi is a pendent if its indegree is equal to 1 and outdegree is 0.
+ Degree of a Node :-
In a directed graph G for any node vertex v the number of edges that
have be as an initial node is the out degree of the node v, The
number of edges that have v as a terminal node is the indegree of
node v and sum of outdegree and indegree is called the total degree.
For an undirected graph the degree or the degree of the
node is equal to the number of node incident with v. The total degree
of loop is two and that of an isolated node is 0.
Indegree 2
62 Royal Education-SYBCA Material
V1 V2
V4 V3
V1 V2
V4 V3
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
Outdegree 0
Total degree 2
b) Loop An edge of a graph which joins a node to itself is called a
loop.
Q.What is a path matrix?
Let G= (V, E) be a simple diagraph which contains n nodes that
are assumed to be ordered. An nxn matrix P whose elements are
given by
P
ij
=1 if there exists a path from v
i
to v
j
=0 otherwise
is called the path matrix of the graph G.
Loop OR Sling: -
An edge of a graph which joins a node to itself is called a Loop or Sling.
Q. Give the different representation of graph
+ Representation of a Graph
A graph can be represented in many ways,
1) Using sets.
2) Using link list.
3) Using matrices.
1 ) Using sets :-
This is one of the striate forward methods of
representing a graph. In this method two sets are maintain. Set v, the
set of vertices, v set e, the set of edges.
63 Royal Education-SYBCA Material
V
4
V
1
V
3
V
2
A B
C D
E
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
V = {A, B, C, D, E}
E = {(A, B) (B, E) (E, D) (D, C) (C, A) (C, B) (A, D) (B, D) (A, C)}
2) Using Link List:-
In this representation two types of node structures are
use depending on the type of the graph.
In link representation the number of list depends on the number of
vertices in the graph. The header nodes in each list maintain a list of
a node for which header node is meant.
3) Using matrices:-
Matrix representation is the most useful way of representing of any
graph. This represent uses a matrix of order n*m when n is the total
no. of vertices in the graph. Let G=(v, e) be a simple diagram in
which v=v1, v2
And the nodes are assumed to b ordered from V1 to Vn. A matrix
Awhose elements Aij are given by,
Aij= {1, if Vi, Vj E and 0, otherwise}
Is called the adjacent matrix of graph G. Any element in the adjacent
matrix is either 0 or 1.
64 Royal Education-SYBCA Material
V1
V2 V3
V4 V5 V6 V7
A B
C D
Royal Education Preparation without Parents Blessing is Stack without Top Pointer

V1 V2 V3 V4
V1 0 1 0 1
V2 0 0 0 1
V3 0 1 0 1
V4 1 0 0 0
1) Write the algorithm for Breadth first search method.
BFS(INDEX)
1.Reach[INDEX]true
DIST [INDEX]0
CALL QINSERT (QUEUE, INDEX)
2. Repeat thru step 5 while queue is not empty
3. Call QDELETE(QUEUE,INDEX)
4.LINKLISTPTR[INDEX]
REPEAT STEP 5 WHILE LINK!= NULL
5. [If this is an unvisited node, label it and add it to the queue
If not REACH [DESTIN (LINK)]

(a) Write the algorithm for DES. What is articulation point?
DFS(INDEX,COUNT)
1. [Update the depth first search number set and mark current
node]
COUNTCOUNT+1
DFN [INDEX] COUNT
REACH [INDEX]TRUE
2.[Set up loop to examine each neighbour of current node]
LINKLISTPTR [INDEX]
Repeat step 3 while LINK! =NULL
3. [If node has not been marked label it and make a recursive call]
If not REACH [DESTIN (LINK)]
Then Call DFS (DESTIN (LINK), COUNT)
LINKEDGEPTR (LINK)
4. [Return to point of call]
65 Royal Education-SYBCA Material
22
11
22
V1 V2
V3 V4
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
Return
Q. Write down the difference between DFS and BFS
DFS BFS
In case of DFS, the concept of
stack is used. The entire
unvisited are pushed in the
stack.
In case of BFS queue is used. All
the unvisited vertices to the one
already visited are placed at the
rear of the queue
DFS picks up vertices all over the
graph (It traverse through the
depth of the graph)
BFS traverse all the vertices close
to the start vertex before
moving to the other vertices
DFS spans very narrow and long
trees
BFS on the other hand creates
very wide and short tree
Show diagram of DFS
Traversal
Show the Diagram of BFS
Traversal
Dijkstras algorithm
Another kind of the shortest path problem is the single source shortest
path problem. In this problem, there is a distinct vertex, called source
vertex and it requires finding the shortest path from this source
vertex to all other vertices.
From v1 to v2 v1-v2 1
From v1 to v3 v1-v2-v3 3
From v1 to v4 v1-v2-v4 4
From v1 to v5 v1-v2-v3-v5 5
66 Royal Education-SYBCA Material
Shoterst Path Length of the shortest path
v1
V2
V3
V4
V5
22
11
22
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
Algorithm KRUSHKAL (informal description)
1. List all of the edges of the graph G in the increasing order of
weights.
2. Select the smallest edge from the list and add it into the spanning
tree (initially it is empty) if the inclusion of this edge does not make a
cycle.
3. If the selected edge with smallest weight forms a cycle, remove it
from the list is empty.
4. Repeat step 2 - 3 until the tree contains n 1 edges and the list is
empty.
5. If the tree T contains less then n 1 edges and the list is empty,
no spanning tree is possible for the graph, else return the minimum
spanning.
2
1
6

-----------------------------------------------
Edge Weight Selection
67 Royal Education-SYBCA Material
V1
V6
V3
V4
V7
V5
V2
4
2
1
3
7
9 6 1 6
6
16
8 6 1 6
4 6 1 6
2 6 1 6
5 6 1 6
V1
V6
V3
V4
V7
V5
V2
22
11
22
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
------------------------------------------------
v2 v4 1
v3 v6 1
v2 v5 2
v1 v4 2
v4 v5 3 x
v1 v2 4 x
v4 v6 4
v1 v3 5 x
v6 v7 6
v4 - v7 7
v3 v4 8
v5 v79
Discuss DFS and draw the DFS spanning tree for the following.
One question, we can answer with graph in figure 3 is can I get from
city x city y on by air-lines? This is similar to ask the question. Does a
path exist in the graph from vertex x to vertex y? Using a DFS. Lets
develop an operation that finds a path from start vertex (x) to end
vertex (y).
We need a systematic way to keep track of cities as we
investigate them. With a DFS. We examine the first vertex that is
adjacent from start vertex, if this is end vertex; the search is over
otherwise we examine all the vertices that are adjacent from this
vertex.
Mean while we need to store the other vertices that are
adjacent fro start vertices. If a path doesnt exist from the first
vertices, we come back and try the second, thirdBecause we want
to travel as far as we can down one path back tracking if the end
vertex is not found, a stack would be a good data structure for storing
vertices. Here is the algorithm.
Depth first search
Found <- False
Create stack (start)
Push (start, start vertex)
Repeat
Pop (stack, vertex)
If vertex = end vertex
Then
{
Print final
Found <- true
}
Else
print the vertex
get adjacent list - (get list adjacent vertices)
push all the adjacent vertices onto stack
Until empty stack (stack) OR Found
68 Royal Education-SYBCA Material
Royal Education Preparation without Parents Blessing is Stack without Top Pointer
If not found
Then print Path does not exist
Q. Prims algorithm
PG 413 D-samanta
69 Royal Education-SYBCA Material