Study Outline For Data Structure
Study Outline For Data Structure
A Study Outline of
A Guidebook of
Data
Structure
Data Structure
====================================================================================================
Email : [email protected]
Publisher : Abu Syed Md Mominul Karim Masum.
Chemical Engr.
Chief Executive Officer (CEO)
Swarm Fashion, Bangladesh.
Mohakhali,Dhaka.
Email : [email protected]
Copyright : Writer
Computer Compose : Writer
Print : Royal Engineering Press & Publications.
Meherchandi, Padma Residential Area, Boalia, Rajshahi.
PRICE :
400.00 TAKA (Fixed Price).
US 05 Dollars (Fixed Price).
N.B: All rights reserved. No part of this work may be reproduced or transmitted in any form
or by any means, Electronic or mechanical, including photocopying, recording, or by any
information storage or retrieval system, without the prior written permission of the
copyright owner and the publisher. It is hereby declared that, if someone or somebody copy
the book or try to copy the book as partially or wholly for personal use or merchandizing, is
punishable offence and the Publisher may take lawful action and can demand 10, 00, 000
(Ten lacks) TK as compensation against them.
Data Structure : Engr. Abu Saleh Musa Miah (Abid).
Published by : Bangladesh Army University of Science and Technology.
Saidpur Cantonment, Saidpur.
Dedicated
To My Parents and honorable Teachers.
†jL‡Ki K_v
Data Structure †Kvm©wU evsjv‡`‡ki cÖvq mKj wek¦we`¨vj‡qi wm‡jev‡m ¯’vb jvf K‡i‡Q,evRv‡i
†U·UeB _vK‡jI Mfxi fv‡e Abyaveb I cix¶vq fvj gvK©m DVv‡bvi gZ mvRv‡bv †U·UeB mnRjf¨
bq | cix¶vi cÖ¯‘wZi ¯^v‡_© ZvB, GB MvBWeBwU Avcbv‡K mn‡hvwMZv Ki‡e e‡j Avkv Kiv hvq|
GB eB‡qi cvVK wn‡m‡e, AvcwbB n‡”Qb me‡P‡q ¸iæZ¡c~Y© mgv‡jvPK ev gšÍe¨Kvix| Avi Avcbv‡`i
gšÍe¨ Avgvi Kv‡Q g~j¨evb, Kvib AvcwbB ej‡Z cvi‡eb Avcbvi Dc‡hvMx K‡i eBwU †jLv n‡jv wKbv
A_©vr eBwU wKfv‡e cÖKvwkZ n‡j AviI fvj n‡Zv| mvgwMÖK e¨vcv‡i Avcbv‡`i †h †Kvb civgk© Avgv‡K
DrmvwnZ Ki‡e|
ACKNOWLEDGEMENTS
I wish to express my profound gratitude to all those who helped in making this book a reality;
especially to my families, the classmates, and authority of Royal Engineering Publications for their
constant motivation and selfless support. Much needed moral support and encouragement was
provided on numerous occasions by my families and relatives. I will always be grateful, to the
numerous web resources, anonymous tutorials hand-outs and books I used for the resources and
concepts, which helped me build the foundation.
I would also like to express my profound gratitude to Engr. Syed Mir Talha Zobaed for his
outstanding contribution in inspiring, editing and proofreading of this guidebook. I am also grateful
to Omar Faruque Khan (Sabbir) for his relentless support and guideline in making this book a
reality.
I am thankful to the following readers those have invested their valuable times to read this book
carefully and have given suggestion to improve this book:
Abu Hurayra (Principle,RESTC)
Engr. Mainuddun Maruf (B.Sc. Engg in Electrical and Electronics Engineering. IUT) .
Md.Moyeed Hossain (B.Sc.Engr. Computer Science and Engineering ,RUET, Lecturere, RESTC).
Md.Shamim Akhtar (B.A Honours,English,M.A. Lecturere, RESTC).
MD.Sharafat Hossain(B.Sc. Engg in Electrical and Electronics Engineering. RUET).
………………………………... And numerous anonymous readers.
I am also thankful to the different hand notes from where I have used lots of solutions, such as
Dynamic Memory Allocation,Operator overloading etc
I wish to express my profound gratitude to the following writers whose books I have used in my
Guidebooks:
…………………….. and Numerous anonymous Power Point Slides and PDF chapters from different
North American Universities.
Data Structure
Syllabus
Books Recommended:
Index
Part-A Marks-26.25
Chapter-1:Arrays
Chapter-2:Stacks,Queues and Recursion
Chapter-3:Recursion.
Chapter-4:Link Lists
Part-B Marks-26.25
Chapter-5: Trees
Chapter-6:Graph
Chapter-7:Symbol Tables
Chapter-8:Files
Part-A Marks-35
Cha
pter
Introductio
0
n to Data
Structure
Important Question
1. Define data structure. Why is data structure necessary? Exam-2016
2. What is data structure? What are the differences between linear and nonlinear data
structure? Exam-2014,2013
3. What do mean by Linear data structure and Nonlinear data structure? Given Example.
Exam-2016
4. Why data structure is needed? Differentiate between linear and nonlinear data structure.
Exam-2015
Data Structure:
The logical or mathematical model of a particular organization of data is called a data
Structure.
Necessary of Structure:
Data structures are important for the following reasons:
Data structures are used in almost every program or software system.
Specific data structures are essential ingredients of many efficient algorithms, and
make possible the management of huge amounts of data, such as large integrated
collection of databases.
Some programming languages emphasize data structures, rather than algorithms,
as the key organizing factor in software design.
Question: What do mean by Linear data structure and Nonlinear data structure? Given Example.
Exam-2016
Answer:
Linear Data Structure:
A data structure is said to be linear if its elements form a sequence or a linear list.
Examples:
Array
Linked List
Stacks
Queues
Examples
Graphs and
Trees.
Question: What is data structure? What are the differences between linear and nonlinear data
structure? Exam-2014,2013
Question: Why data structure is needed? Differentiate between linear and nonlinear data structure.
Exam-2015
Answer:
They are easy to implement in They are difficult to implement in computer’s memory since
computer’s memory since they are the data element can be attached to various other data
organized sequentially. elements.
Answer:
The operations one normally performs on any linear structure, whether it he an array or
a linked
list, include the following:
Cha
pter 1
Aarrays
Important Question
1. Explain linear array representation in memory. Exam-2015
2. How can you traverse an array? Exam-2013
3. Simulate the binary search algorithm on the following
data:10,20,50,70,80,90,100,110(suppose we search for item 110). Exam-2015
4. Simulate the binary search algorithm on the following data:12 14 16 18 20 22 24 26 28
30(suppose we search for iteam 23). Exam-2013
5. Is it possible to apply binary search on unsorted data? Justify your answer. Exam-2013
6. For column major order find out the address of the element score[15,3] from a 20X5
matrix array score with base value 100 and w=4. Exam-2015
7. For column major order find out the address of the element score[5,2] from a 20X4 matrix
array score with base value 150 and w=4. Exam-2013
8. What do you mean by internal and external sorting ? List some names of each type. Exam-
2014
9. For column major order find out the address of the element marks[12,3] from a 25X4
matrix array marks with base value 250 and w=8. Exam-2014
10. What is pointer and pointer array? Exam-2014
11. How a pointer can save memory space to store a 2D array? Exam-2014
12. How does a pointer array can save memory when stores a variable sized group of
data?Discuss with necessary figures. Exam-2015
13. What is a record? What is the difference between a record and a linear array? Exam-2015
14. What is sparse matrix? What is the difference between triangular matrix and tridiagonal
matrix? Exam-2013,2014
15. How can you locate the element aij of a sparse matrix from a ID array? Exam-2013
16. What is sparse matrix? What is the difference between triangular matrix and Tridiagonal
matrix? Exam-2016
17. What are the disadvantages of array implementation of list? Exam-2013
Let LA be a linear array in the memory of the computer. In Fig. 4-2. Let us use the notation
Computer needs to keep track only of the address of the first element of LA, denoted by
Base( LA)
and called the base address of LA. Using this address Base(LA), the computer calculates the
address of any element of LA by the following formula:
Example:
Arays can be declared in various ways in different languages. For illustration, let's take C array
declaration.
As per the above illustration, following are the important points to be considered.
Let A be a collection of data elements stored in the memory of the computer. Suppose we
want to print the contents of each clement of A. This can be accomplished by traversing A, that is, by
accessing and processing (frequently called visiting) each clement of A exactly once.
If a data entry is added to or removed from an array-based list, data needs to be shifted to
update the list.
In the worst case, for an array-based list with n data entries, an add and a remove takes
o(n) time.
Also, all data in the array-based list must be stored sequentially in memory. Large lists will
require significant contiguous blocks of memory.
Question: What is Binary Search algorithm and How its Works Explain with Example?
Binary Search Algorithm:
Binary search looks for a particular item by comparing the middle most item of
the collection. If a match occurs, then the index of item is returned. If the middle item is greater than
the item, then the item is searched in the sub-array to the left of the middle item.
Note that the variables BEG and END denote, respectively, the beginning and end locations of the
segment under consideration. The algorithm compares ITEM with the middle clement DATA[MID]
of the segment, where MID is obtained by
MID = INT((BEG + END)/2) (We use INT(A) for the integer value of A.)
(a) If ITEM < DATA[MID], then ITEM can appear only in the left half of the segment:
DATA[BEG], DATA[BEG +11 .....DATA[MID —1]
So we reset END : = MID - 1 and begin searching again.
(b) If ITEM> DATA[MID], then -ITEM can appear only in the right half of the segment:
DATA[MID + fl DATA[MID + 2]..... DATA [END]
So we reset BEG := MID + 1 and begin searching again.
EXAMPLE
Let DATA be the following sorted 13-clement array:
DATA: 11, 22, 30, 33, 40, 44, , 60, 66, 77, 80, 88, 99
We apply the binary search t o DATA for 'different values of ITEM.
Suppose ITEM = 40. The search for ITEM in the array DATA is pictured in Fig. 4-6, where the
values of DATA[BEG] and DATA[END] in each stage of the algorithm are indicated by circles and
the value of DATA Specifically, BEG, END and MID will have the following successive values:
(2) Since 40< 55, END has its value changed by END = MID - 1 =6
Hence MID = INT [(1 + 6)/2 = 3 and so DATALMID] = 30
(3) Since 40>30, BEG has its value changed by BEG = MID + 1=4
Hence MID INT[4 + 6)/2]=5 and so DATA[MID]=40
We have found ITEM in location LOC MID= 5.
Suppose ITEM = 85. The binary search for ITEM is pictured in Fig. 4-7. Here BEG. END and MID will
have the following successive values:
(2) Since 85>55, BEG has its value changed by BEG = MID + 1= 8. Hence
MID INTL(8 + 13)/21 10 and so DATALMIDJ 77
(3) Since 85>77, BEG has its value changed by BEG MID + 1= 11.
Hence MID = INT[(1 I + 13)/2]= 12 and so DATA(MID]=88
(4) Since 85< 88, END has its value changed by END = MID – 1=11.
Hence MID INT[(1I + 11)/2] =11 and so DATA[MID]= 80
(Observe that now BEG = END MID = 11.)
Since 85> 80, BEG has its value changed by BEG = MID + 1=12. But now BEG> END. Hence ITEM
does not belong to DATA.
Or
The following is our sorted array and let us assume that we need to search the location of value 31
using binary search.
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that
the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have a
sorted array, so we also know that the target value must be in the upper portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
The value stored at location 7 is not a match, rather it is less than what we are looking for. So, the
value must be in the lower part from this location.
We compare the value stored at location 5 with our target value. We find that it is a match.
Answer:
Here item=110
10 20 50 70 80 90 100 110
BEG=1 2 3 MID=4 5 6 7 END=8
(2) Since 110>70 , BEG has its value changed by BEG= MID + 1 =5
Hence MID = INT [(5 + 8)/2 = 6 and so DATA [MID] = 90
(3) Since 110>90 , BEG has its value changed by BEG= MID + 1 =7
Hence MID = INT [(7 + 8)/2 = 7 and so DATA [MID] = 100
(4) Since 110>100 , BEG has its value changed by BEG= MID + 1 =8
Hence MID = INT [(8 + 8)/2 = 8 and so DATA [MID] = 110
We have found ITEM in location LOC MID=8.
Answer:
Here item=23
12 14 16 18 20 22 24 26 28 30
BEG=1 2 3 4 MID=5 6 7 8 9 END=10
(2) Since 23>20 , BEG has its value changed by BEG= MID + 1 =6
Hence MID = INT [(6+ 10)/2 = 8 and so DATA [MID] = 26
(3) Since 23<26 , END has its value changed by END= MID -1 =7
Hence MID = INT [(6 + 7)/2 = 6 and so DATA [MID] = 22
(4) Since 23>22 , BEG has its value changed by BEG= MID + 1 =7
Hence MID = INT [(7 + 7)/2 = 7 and so DATA [MID] = 24
We have not found ITEM in location LOC MID=7
Question: Is it possible to apply binary search on unsorted data? Justify your answer. Exam-2013
Answer:
We could apply. But we most probably would miss the element you’re searching for. Because
binary search works based on the assumption/ invariant (for elements in increasing order) that
whenever we are in a position all the elements to its left lower than itself and all the elements to its
right are greater than itself. Which is useful to decide which side to search further.
But in the case of unsorted list, the element you’re searching may be in any side of the array from
your current position.So we’ve to search the both sides of the list, which is linear.
Question: For column major order find out the address of the element score[15,3] from a 20X5
matrix array score with base value 100 and w=4. Exam-2015
Question: For column major order find out the address of the element score[5,2] from a 20X4 matrix
array score with base value 150 and w=4. Exam-2013
Question: What do you mean by internal and external sorting ? List some names of each type. Exam-
2014
Question: For column major order find out the address of the element marks[12,3] from a 25X4
matrix array marks with base value 250 and w=8. Exam-2014
Answer:
Consider the 25 x 4 matrix array SCORE in Example 4.11. Suppose Base(SCORE) = 200 and there
arew = 4 words per memory cell. Furthermore, suppose the programming language stores two-
dimensional arrays
using row-major order. Then the address of SCORE[12. 31, the third test of the twelfth student,
follows:
LOC(SCORE[12. 3]) = 200 + 4(4(12 - 1) + (3– 1)] = 200 + 446] = 384
Observe that we have simply used Eq. (4.5).
Pointer Array:
An array PTR is called a pointer array if each element of PTR is a pointer.
Pointers and pointer arrays are used to facilitate the processing of the information in DATA. This
section discusses- this useful tool in the context of a specific example.
Question: How a pointer can save memory space to store a 2D array? Exam-2014
Question: How does a pointer array can save memory when stores a variable sized group of data?
Discuss with necessary figures. Exam-2015
Question: What is a record? What is the difference between a record and a linear array? Exam-2015
Answer:
Record:
A record is a data structure made up of a fixed number of information items, not necessarily of
the same type.
Or
A record is a collection of related data items, each of which is called a field or Attribute, and it file is
a collection of similar records.
Question: What is sparse matrix? What is the difference between triangular matrix and tridiagonal
matrix? Exam-2013,2014,2016
Answer:
Sparse Matrices
Matrices with a relatively high proportion of zero entries are called sparse matrices. Two
general types of n-square sparse matrices which occur in various applications.
Triangular matrix
The first matrix, where all entries above the main diagonal are zero or, equivalently,
where nonzero entries can only occur on or below the main diagonal, is called a (lower) triangular
matrix.
Tridiagonal Matrix
The second matrix, where nonzero entries can only occur on the diagonal or on
elements immediately above or below the diagonal, is called a tridiagonal matrix
Question: How can you locate the element aij of a sparse matrix from a ID array? Exam-2013
Answer:
Suppose we want to place in memory the triangular array A in Fig. 4-22. Clearly it would be
wasteful to store those entries above the main diagonal of A, since we know they are all zero; hence
we store only the other entries of A in a linear array B as indicated by the arrows. That is, we let
B[1J=a11, B[2]=a21, B[31=a22 , B(3]=a31,
Observe first that B will contain only
1+2+3+4++nn(n+l)
elements, which is about half as many elements as a two-dimensional n X n array. Since we will
require the value of a, in our programs, we will want the formula that gives us the integer L in
terms of J and K where B[L]a,K
Cha
pter
Stack
2
,Queues
and
Recursion.
Important Question
1. What is stack ?What are the operations on stack? Explain with example . Exam-2015,2013
2. Discuss the array representation mechanism of stack. Exam-2016,2013
3. What is polish notation? What are the benefits of polish notation? Exam-2016,2014
4. Simulate the postfix expression evaluation algorithm using 12,6,7,6,2,+,*,12,4,/,- by
showing Stact’s contents as each element is scanned. Exam-2016,2014
5. Simulate the infix to postfix transformation algorithm for- A+(B*C-(D/E↑F)*G)*H by
showing the stack’s contents as each element is scanned. Exam-2013
6. Convert the following infix expression to its equivalent prefix and postfix expression.
(i) A*B/C+D↑ (E-F*G)/H
(ii) 1+2*3/4↑ 5*6-7*8 Exam-2016
7. Convert the following infix expression to its equivalent prefix and postfix expression.
(i) A*B+(C*D/E)*F+(G↑ H)
(ii) 1*2/3+(4-5↑6)+7-8 Exam-2014
8. Convert the following infix expression to its equivalent prefix and postfix expression
(i) A+B*C/D-E(F/G+H↑K)
(ii) (1+2)↑3/4*5+7-8↑ 9 Exam-2015
9. Convert the following infix expression into their equivalent prefix and postfix expressions:
Exam-2013
(i) A+B*C/(D-E)+F/G*H
(ii)10*B+5/D-(12+F)/50
Question: What is stack ?What are the operations on stack? Explain with example . Exam-2015,2013
Answer:
Stack:
Stack is an ordered list of similar data type its a LIFO structure. (Last in First out).
A stack is a list of elements in which an element may be inserted or deleted only at one end, called
the lop of the stack. This means, in particular, that element removed from a stack in the reverse
order of that in which they were inserted into the stack.
Operation of Stack:
Special terminology is used for two basic operations associated with stacks:
EXAMPLE 6.1
Suppose the following 6 elements arc pushed, in order, onto an empty stack:
AAA, BBB, CCC, ODD, EEE, FFF
Figure 6-3 shows three waxs of-picturing such a stack. For notational stack by writing:
STACK: AAA, BBB CCC, ODD, EEE, FFF
The implication is that the right-most clement is the top clement.
means of a one-way list or a linear array. a pointer variable TOP, which contains the location of the
top clement of the stack; and a variable MAXSTK which gives the maximum number of elements that
can be held by the stack. The condition TOP = 0 or TOP = NULL will indicate that the stack is empty.
We note that the value of TOP is hanged before the insertion in PUSH but the value of TOP is
changed after the deletion in POP.
Question: What is polish notation? What are the benefits of polish notation? Exam-2016,2014
Polish Notation
Polish notation also known as prefix notation is defined as: In this notation system
operator is written before the operands.
Example of polish notation or prefix notation is +AB or /CD. In these two examples we
can see that here A and B are two operands and + is an operator which is written before operands,
similarly we can say for the second example.
The conversion of an infix expression into prefix notation is shown belowConvert the infix
expression (A + B) x (C + D) into prefix notation?
SOLUTION
(A + B) x (C + D)
= [+AB] x [+CD]
= x [+AB+CD]
= x+AB+CD
So prefix notation is x+AB+CD.
The elements of 0 have now been labeled from left to right for easy reference. Figure 6-8 shows the
status of
STACK and of the string I' as each element of 0 is scanned. Observe tIt:iI
(I) Each operand is simply added to P and does not change STACK.
(2) The subtraction operator (-) in row 7 sends * front to P before it (-) is pushed onto STACK.
(3) The right parenthesis in row 14 scnds t and then / from STACK to P. and then removes the left
parenthesis Ironi he top of STACK.
(4) The right parenthesis in row 20 sends * and then + from STACK to P. and (lien removes the left
parenthesis from the top of STACK.
After Step 20 is executed, the STACK is empty and
P: ABCI)EF 1/G - 11* +
which is the required postlix equivalent of 0.
Question: Convert the following infix expression to its equivalent prefix and postfix expression.
(i) A*B/C+D↑ (E-F*G)/H
(ii) 1+2*3/4↑ 5*6-7*8 Exam-2016
Question: Convert the following infix expression to its equivalent prefix and postfix expression.
Question: (i) A*B+(C*D/E)*F+(G↑ H)
(ii) 1*2/3+(4-5↑6)+7-8 Exam-2014
Question: Convert the following infix expression to its equivalent prefix and postfix expression
(i) A+B*C/D-E(F/G+H↑K)
(ii) (1+2)↑3/4*5+7-8↑ 9 Exam-2015
Question: Convert the following infix expression into their equivalent prefix and postfix expressions:
Exam-2013
(i) A+B*C/(D-E)+F/G*H
(ii)10*B+5/D-(12+F)/50
Queues are also called first-in first-out (FIFO) lists, since the first clement i1 a queue will be the
first element Out of the queue. In other words, the order in which elements enter a queue is the
ABU SALEH MUSA MIAH(ABID) +880-1734264899 Page 27
order in which they leave. This contrasts with stacks, which are last-in first-out (LIFO) lists.
EXAMPLE 6.9
Figure 6-15(a) is a schematic diagram of a queue wilts 4 elements, where AAA is the front
clement and DDD is the rear element. Observe that the front and rear elements of the queue
are also, respectively, the first and last elements of the list. Suppose an element is deleted
from the queue. Then it must he AAA.
This yields the queue in Fig. 6-15(b), where BBB is now the front clement. Next, suppose
EEE is added to the queue and then FEF is added to the queue.
Then they must be added at the rear of the queue, as pictured in Fig. 6-15(c), Note that FFF
is now the rear clement.
Now suppose another element is deleted from the queue; then it must he BBB, to yield the
queue in Fig. 6-15(d). And soon. Observe that in such a data structure, EEE will he deleted
before FFF because it has been placed in the queue before FFF. However, EEE will have to
wait until CCC and DDI) are deleted.
1TY QUEUES
Priority Queue:
A priority queue is an abstract data type which is like a regular queue or stack data
structure, but where additionally each element has a "priority" associated with it. In a priority queue,
an element with high priority is served before an element with low priority.
Or
Priority queue is a collection of elements such that each clement has been assigned if and
such that the order in which elements arc deleted and processed comes from the following rules:
(1) An element of higher priority is processed before any clement of lower priority.
(2) Two elements with the same priority arc processed according to the order in which they were
added to the queue.
A prototype of a priority queue is a timesharing system: programs of high priority are processed
first, programs with the same priority form a standard' queue. There are various ways of
maintaining a priority queue in memory. We discuss two of them here: One uses a one-way list, and
the other uses multiple queues. The ease or difficulty in adding elements to deleting them from a
priority queue clearly depends on the representation that one chooses.
Figure 6-19
Shows a Schematic diagram of a priority queue with 7 elements. The diagram does not tell
us whether BBB was added to the list before or after DDD. On the other hand, the diagram does tell
us that BBB was inserted before CCC. because BBB and have the same priority number and BBB
appears before CCC in the list. Figure 6-20 show the way the priority queue may appear in memory
using linear arrays INFO PRN and LINK.
Question: What is overflow and underflow? How can you handle them? Exam-2014
Stack overflow:
Sometimes new data are to be inserted into a data structure but there is no available
space, i.e., the free-storage list is empty. This situation is usually called overflow.
Or
Stack overflow happens when we try to push one more item onto our stack than it can
actually hold the stack usually can only hold so much stuff. Typically, we allocate (set aside) where
the stack is going to be in memory and how big it can get. So, when we stick too much stuff there or
try to remove nothing, we will generate a stack overflow condition or stack underflow condition,
respectively.
Handle Overflow:
The programmer may handle overflow by printing the message OVERFLOW. In such a case,
the programmer may (hen modify the program by adding space to the underlying arrays. Observe
that overflow will occur with our linked lists when AVAIL = NULL and there is an insertion.
Stack underflow
The term underflow refers to the situation where one wants to delete data from a Data
structure that is empty.
Or
Stack underflow happens when we try to pop (remove) an item from the stack,
when nothing is actually there to remove. This will raise an alarm of sorts in the computer, because
we told it to do something that cannot be done.
Handle Underflow:
The programmer may handle underflow by printing the message Underflow
observe that underflow will occur with our linked lists when start null and There is a deletion,
Garbage Collection
The operating system of a computer may periodically collect all the deleted space
on to the free-storage list. Any technique which does this collection is called Onto the garbage
collection.
When it place:
Garbage collection usually takes place in two steps.
First: The computer runs through all lists, tagging those cells which are currently in use, and then
the computer runs through the memory
Second: collecting all untagged space onto the free-storage list. The garbage collection may take
place when there is only some minimum amount of space or no space at all left in the free-storage
list, or when the CPU is idle and has time to do the collection.
Generally speaking, the garbage collection is invisible to the programmer.
Compaction:
Data compaction is the reduction of the number of data elements, bandwidth, cost, and
time for the generation, transmission, and storage of data without loss of information by eliminating
unnecessary redundancy, removing irrelevancy, or using special coding.
Cha
pter 3
Recursion.
Important Question
Question: What is recursion? Explain the use of recursion. Exam-2016
Answer:
Recursion:
Recursion is an approach in which a function calls itself with an argument. Upon reaching
a termination condition, the control returns to the calling function.
Or
A more common way to use recursion in programming is to base the recursion on a
recursive data structure. A data structure is recursive if we can define it in terms of itself. For
example, we can give a recursive definition of a string: A string is either empty, or it is a character
followed by a string.
Use of Recursion:
When are some (relatively) basic (think first year college level CS student) instances when
one would use recursion instead of just a loop?
Space is carved out on the stack for the function's arguments and local variables
The function's arguments are copied into this new space
Control jumps to the function
The function's code runs
The function's result is copied into a return value
The stack is rewound to its previous position
Control jumps back to where the function was called
Ch
apt
er
4
Links Lists.
Important Question
1. What the advantage Linked List? Exam-2016
2. Suppose 10 elements are maintained by array and another 10 are by Linked List. Which
methods take longer time to access 7th element. Justify your answer. Exam-2016
3. Briefly discuss inserting and deleting mechanism of an item in the linked list. Exam-2016
4. Explain the representation of linked lists in memory. Exam-2015
5. List the advantage and disadvantage of Linked list. Exam-2013
6. Show with appropriate schematic diagram how insertion and deletion could be carried
out into a singly linked list. Exam-2013
7. Discuss header linked list. Describe grounded and circular header list. Exam-2015
8.
9. What is a linked List? Discuss with example. Exam-2014
10. Suppose 20 elements are maintained by array and another 10 are by Linked List. Which
methods take longer time to access 9th element. Justify your answer. Exam-2014
11. Briefly discuss inserting mechanism of an item at the beginning, after a given node and at
the end. Exam-2014
12. Briefly explain two-way linked list. Exam-2015
13. What is a two way list? Why is it important? Explain with schematic diagram. Exam-
2014,2016
Question: What is linked list? What the advantage Linked List? Exam-2016
Question: What is a linked List? Discuss with example. Exam-2014
Question: List the advantage and disadvantage of Linked list. Exam-2013
Answer:
Link List:
A linked list, or one-way list- is a linear collection of data elements, called nodes, where the
linear order is given by means of pointers.
That is, each node is divided into two parts: the first part contains the information of the clement,
and the second part, called the link field or next pointer field, contains the address of the next node
in the list.
PTR: = LINK[PTR]
moves the pointer to the next node in the list, as pictured in Fig. 5-8.
Question: Briefly discuss inserting mechanism of an item at the beginning, after a given node and at
the end. Exam-2014
Question: Briefly discuss inserting and deleting mechanism of an item in the linked list. Exam-2016
Question: Show with appropriate schematic diagram how insertion and deletion could be carried
out into a singly linked list. Exam-2013
insertion appears in Fig. 5-14(b). That is, node A now points to the new node N, and node N points
to node B, to which A previously pointed
Question: Discuss header linked list. Describe grounded and circular header list. Exam-2015
Header Linked List:
A header linked list is a linked list which always contains a special node, called the
header node, at the beginning of the list.
(1) A grounded header list is a header list where the lost node contains the null pointer. (The
term "grounded" comes from the fact that many texts use the electrical ground symbol to
indicate the null pointer.)
(2) A circular header list is a header list where the last node points bock to the header nodc.
Figure 5-29 contains schematic diagrams of these header lists. Unless otherwise stated or implied,
our header lists will always be circular. Accordingly, in such a case, the header nodc also acts as a
sentinel indicating the end of the list.
Observe that the list pointer START always points to the header node. Accordingly. LINK[STARTJ =
NULL indicates that a grounded header list is empty, and LINKISTARTI START indicates that a
circular header list is empty
A two-way list is a linear collection of data elements, called nodes, where each node N is divided
into three parts:
(1) An information field INFO which contains the data of N
(2) A pointer field FORW which contains the location of the next node in the list
(3) A pointer field BACK which contains the location of the preceding node in the list
The list also requires two list pointer variables: FIRST, which points to the first node in the list, and
LAST, which points to the last node in the list.
Observe that, using the variable FIRST and the pointer field FORW, we can traverse a two-way list
in the forward direction as before. On the other hand, using the variable LAST and the pointer field
BACK, we can also traverse the list in the backward direction.
Suppose LOCA and LOCB are the locations, respectively, of nodes A and B in a two-way list. Then
the way that the pointers FORW and BACK are defined gives us the following:
In other words, the statement that node B follows node A is equivalent to the statement that node A
precedes node B.
Two-way lists may be maintained in memory by means of linear arrays in the same way as one-
way lists except that now we require two pointer arrays, FORW and BACK, instead of one pointer
array LINK, and we require two list pointer variables, FIRST and LAST, instead of one list pointer
variable START. On the other hand, the list AVAIL of available space in the arrays will still be
maintained as a one-way list—using FORW as the pointer field—since we delete and insert nodes.
only at the beginning of the AVAIL list.
Traversal of a doubly linked list can be in either direction. In fact, the direction of traversal
can change many times, if desired. Traversal is often called iteration, but that choice of
terminology is unfortunate, for iteration has well-defined semantics (e.g., in mathematics)
which are not analogous to traversal
Question: Suppose 20 elements are maintained by array and another 10 are by Linked List. Which
methods take longer time to access 9th element. Justify your answer. Exam-2014
Question: Suppose 10 elements are maintained by array and another 10 are by Linked List.
Which methods take longer time to access 7th element. Justify your answer. Exam-2016
Answer:
To Access 7th element from a list,
1.To Access 7th element from Linked list need more time then arrays.
Because in array
If a is array with 10 element a[10];
We can access 7th element by a[7] either insert or delete.
Part-B Marks-35
Cha
pter 5
Trees.
Important Question
1. Simulate the preorder traversal algorithm for the following tree. Exam-2016
12. Define heap, leaf and depth of tree. For 5009 nodes, find out the depth of tree. Exam-2014
13. Discuss the linked representation of binary tree in memory. Exam-2014
14. Simulate the preorder traversal algorithm for the following tree. Exam-2014
15. Simulate the preorder traversal algorithm for the following tree. Exam-2016
Basic Terminology:
A tree consists of a collection of elements or nodes, with each node linked to its successors
A binary tree T is frequently presented by means of a diagram. Specifically, the diagram in Fig. 7-1
represents a binary tree T as follows.
(I) T consists of 11 nodes, represented by the letters A through L, excluding I.
(II) The root of T is the node A at the top of the diagram,
(III) A left-d Own ward slanted line from a node N indicates a left successor of N, and a
right-downward slanted line from N indicates a right successor of N. Observe that:
Any node N in a binary tree T has either 0, 1 or 2 successors. The nodes A, B, C and H have two
successors, the nodes E and J have only one successor, and the nodes D, F, G, L and K have no
successors. The nodes with no successors arc called terminal nodes.
Copy of Tree:
In particular, the trees (c) are copies since they also have the same data at
corresponding nodes
The tree (b) is neither similar nor a copy of the tree (d) because, in a binary tree, we distinguish
between a left successor and a tight successor even when there is only one successor.
Question: What is complete binary tree? What is the parent-child relationship? Exam-2015
Thus there is a unique complete tree . with exactly nodes (we are, of course, ignoring the
contents of the nodes). The complete tree . with 26 nodes appears in Fig. 7.4.
The nodes of the complete binary tree in Fig. 7-4 have been purposely labeled by the integers
1, 2.....26, from left to right, generation • by generation. With this labeling, one can easily determine
the children and parent of any node K in any complete tree T.
Specifically, the left and right children of the node K arc, respectively, and + and the
parent of K is the node / . For example, the children of node 9 are the nodes 18 and 19, and its
parent is the node / . The depth d of the complete tree T. with n nodes is given by
+ . This is a relatively small number. For example, if the complete tree T. has n =
1000000 nodes, then its depth D,=21.
Parent-Child Relationship :
The term parent-child relationship refers to the unique and enduring bond
between a caregiver and his or her child.
To understand the parent-child relationship, we must look at the ways that parents and children
interact with one another physically, emotionally, and socially. Think about your parents. How did
your relationship with your parents contribute to who you are today, or did it? Many psychologists
believe that the relationships between parents and children are very important in determining
who we become and how we relate to others and the world.
A heap is an array , where there are parent child relationships, and the index of a child is 2 * parent
index, or 2* parent index + 1 , and a child has an order after the parent, in some concrete ordering
scheme injected by a client program of a heap. There is importance in maintaining the ordering n
variant after the heap is changed. Some ( Sedgewick and Wayne), have coined the term "swim" and
"sink", where maintenance of the invariant involves a invariant breaking item swimming up above
children of lower ordering, and then sinking below any children of higher ordering, as there may be
two children , so one can swim above a lower ordered child, and still have another child with
higher ordering
Question: What is traversing of a tree? Explain each type of traversing of a Tree Explain with
example.
There are three standard ways of traversing a binary tree T with root R. These three algorithms,
called preorder, inorder and postordcr, are as follows:
Preorder: HLR
(1) Process the root R.
(2) Traverse the left suhtrcc of R in prcordcr.
(3) Traverse the right subticc of R in pre.ordcr.
In order: LHR
(I) Traverse the left subtree of R in inorder.
(2) Process the root R.
(3) Traverse the right suhtrcc of R in inordci.
Post Order: LRH
(1) Traverse the left subtrec of R in postordcr.
.(2) Traverse the right subtrec of R in postorder.
(3) Process the root R.
Observe that each algorithm contains the same three steps, and that the left suhtrce of R is always
traversed before the right subtree. The difference between the algorithms is the time at which the
root R is processed. Specifically, in the "pie" algorithm, the root R is processed before the subtrces
are traversed; in the "in" algorithm, the root R is processed between the ti'avcrsal of the subtrecs;
and in the -rot" algorithm, the root R is processed after the subtrces arc traversed.
EXAMPLE 7.6
Consider the tree Tin Fig. 7-12. The preorder traversal of T is ABDEFCGHJLK. This order is the
same as the one obtained by scanning the tree from the left as indicated by the path in Fig. 7-12.
(Inorder) D B F E A 0 C L 3 H K
(Postorder) F E B 0 L 3 K H C A
Example:
Question: For the expression: *+a-bc*-de/fgh draw the tree and perform inorder and postorder
traversal. Exam-2015
Answer:
The reader can also verily that these orders correspond precisely to the prefix and
postlix Polish
Question: What is binary search tree? Why binary search tree is important ? Exam-2016.,2013
Question: What is binary search tree? Exam-2015
Answer:
The value at N is greater than every value in the left subtree of N and
N is less than every value in the right subtree of N. (It is not difficult to see that this property
guarantees that the inorder traversal of T will yield a sorted listing of the elements of T.)
Suppose the 23 were replaced by 35. Then T would still be a binary search tree. On the other hand,
suppose the 23 were replaced by 40. Then T would not be a binary search tree, since the 38 would
not be greater than the 40 in its left subtree.
Suppose an ITEM of information is given. The following algorithm finds the location of ITEM in
the binary search tree 'I', or inserts ITEM as a new node in its appropriate place .n the tree.
EXAMPLE 7.14
(a) Consider the binary search tree Tin Fig. 7-21. Suppose ITEM 20 is given. Simulating the
above algorithm, we obtain the following steps:
1. Compare ITEM 20 with the root, 38, of the tree T. Since 20< 38, proceed to the left child of 38,
which is 14.
2. Compare ITEM = 20 with 14. Since 20> 14, proceed to the right child of 14, which is 23.
3. Compare ITEM 20 with 23. Since 20<23, proceed to the left child of 23, which is .18.
4. Compare ITEM = 20 with 18. Since 20> 18 and 18 does not have a fight child, insert 20 as the
right child at 18.
Figure 7-22 shows the new tree with ITEM = 20 inserted. The shaded edges . indicate the path
down through the tree during the algorithm.
EXAMPLE 7.15
Suppose the following six numbers arc inserted in order into an empty binary search tree:
40, 60, 50, 33,9ik, 55, II
Figure 7-23 shows (he six stages of the tree. We emphasize that if the six numbers were given in a
different order then the tree might be different and we might have a different depth.
Question: Suppose the following six numbers are inserted into an empty binary search tree
:33,50,45,52,12,10.Show the tree as each number is inserted into a binary search tree. Exam-2015 .
33 33 33 33
60 60 60
45 45
(1) Item=33 2.Item=60
3.Item=45
52
4.Item=4
5
33
60
12
45
10
52
5.Item=4
5
Question: Suppose the following six numbers are inserted in order into an empty binary search
tree:35,55,45,35,52,10,9 show the tree as each number is inserted into a binary search tree. Exam-
ABU SALEH MUSA MIAH(ABID) +880-1734264899 Page 53
2013
35 35 35
55 55
45
1.Item=35 2.Item=55
3.Item=45
33
35
35
60
55 10
55
45
45
45 9
35 52
35 52 6.Item=1,9
4.Item=35 5.Item=52
Question: Define heap, leaf and depth of tree. For 5009 nodes, find out the depth of tree. Exam-2014
Heap of a Tree:
A heap is a specialized tree-based data structure that satisfies the heap property:
If A is a parent node of B, then the key (the value) of node A is ordered with respect to the key of
node B with the same ordering applying across the heap.
Or
Heap is a special case of balanced binary tree data structure where the root-node key is compared
with its children and arranged accordingly. If α has child node β then −
( ) ( )
As the value of parent is greater than that of child, this property generates Max Heap. Based on this
criteria, a heap can be of two types
Max Heap
Min Heap
Leaf of a Tree:
A terminal node is called a leaf, and a path ending in a
leaf is called a branch.
Or
An internal node (also known as an inner node, inode
for short, or branch node) is any node of a tree that has child nodes.
Similarly, an external node (also known as an outer node, leaf node,
or terminal node) is any node that does not have child nodes.
Depth of a Tree:
The depth (or height) of a tree T is the maximum number of nodes in a branch of T.
Or
The height of a node is the length of the longest downward path to a leaf from that
node. The height of the root is the height of the tree. The depth of a node is the length of the path to
its root (i.e., its root path).
77 77 90 90
40 40 77 65 77
90 90 95
65 77 65 77 65 90
40 35 40 35
40 20 20 77
20
95 95
65 90 65 90
40 20 77 40
35 35 77
10 10 15
7.Item=10 7.Item=15
Question: Simulate the maxheap algorithm for the following values:77,39,95,60,23,39,91,9,12 Exam-
2013
77 77 90 90
39 40 77 65 77
90 90 95
65 77 65 77 65 90
40 35 40 35
40 20 20 77
20
95 95
65 90 65 90
40 20 77 40
35 35 77
10 10 15
7.Item=10 7.Item=15
Question: Simulate the preorder traversal algorithm for the following tree. Exam-2014,2016
Question: What is the difference between maxheap and min heap? Exam-2016
Answer:
There's no real difference between min and max heaps, except how the comparison is
interpreted.
Cha
pter 6
Graphs.
Important Question
1. Define weighted graph and directed graph with example. Exam-2016
( )
Now find out A2,A3,A4,B4 and from that make the path matrix and tell whether this is strongly
connected or not. Exam-2013
8. Consider the following adjacency matrix below:
( )
Now find out A2,A3,A4,B4 and from that make the path matrix and tell whether this is strongly
connected or not. Exam-2014
9. Consider the following adjacency matrix below:
( )
Now find out A2,A3,A4,B4 and from that make the path matrix and tell whether this is strongly
connected or not. Exam-2015
10. Consider the following adjacency matrix below:
( )
Now find out A2,A3,A4,B4 and from that make the path matrix and tell whether this is
strongly connected or not. Exam-2016
11. Use the Warshall’s algorithm to find the shortest path matrix of the weighted matrix given
below. Exam-2016
1( )
21. Consider the adjacency list of the graph G in the following table. Find the nodes that are
reachable from node C using Depth first search. Exam-2016
Suppose e = [u, vJ. Then the nodes u and v are called the endpoints of e, and u and u arc said to be
adjacent nodes or neighbors. The degree of a node u, written deg(u), is the number of edges
containing u. If deg(u) = 0—that is, if u does not belong to any edge—then u is called an isolated
node.
Directed Graph:
A directed graph G, also called a digraph Or graph, is-the same as a multigraph except that
each edge e in G is assigned a direction, or in other words, each edge e is identified wiih an ordered
pair (u, v) of nodes in G rather than an unordered pair [u, v].
Suppose G is a directed graph with a directed edge e = (u, v). Then e is also called an arc.
Moreover, the following terminology is used:
(1) e begins at u and ends at v -
(2) u is the origin or initial point of e, and u is the destination or terminal point of e.
(3) u is a predecessor of v, and v is a successor or neighbor of u.
(4) u is adjacent to v, and v is adjacent to u.
Question: Define the following terms: Path, Cycle, Connected Graph and Multi-graph. Exam-2013
Question: Define the following terms: (i)Degree of a node,(ii)Isolated node,(iii)Path,(iv)Multi Graph.
Exam-2015
Degree of node:
The degree of vertex is number of edges that are connected to the vertex. In figure
un directed graph, degree of vertex-1 is 2 and vertex 3 is 3.
In Degree: This is applicable only for directed graph. This represents the number of edges incoming
to a vertex. In above directed graph, degree of 1 is 0 and degree of 2 is 2.
Out degree: This is also applicable only for directed graph. This represents the number of edges
outgoing from a vertex. In above directed graph, degree of 1 is 2 and degree of 2 is 0.
Degree of Graph: Sum of degrees of all the vertices of G
Isolated node:
An isolated vertex is a vertex with degree zero
Path:
a path in a graph is a finite or infinite sequence of edges which connect a sequence
of vertices which, by most definitions, are all distinct from one another.
In a directed graph, a directed path (sometimes called dipath) is again a sequence of edges (or
arcs) which connect a sequence of vertices, but with the added restriction that the edges all be
directed in the same direction.
Multi Graph:
A multigraph is a graph which is permitted to have multipleedges (also called
parallel edges), that is, edges that have the same end nodes. Thus two vertices may be connected by
more than one edge.
Or
A cycle is a closed simple path with length 3 or more. A cycle of length k is called a
k-cycle.
Connected graph:
Graph G is connected if and only if there is a simple path between any two nodes In G.
Adjacency Matrix:
Suppose G is a simple directed graph with in nodes, and suppose the nodes of G have
been ordered and are called , , , … … . . . Then the adjacency Matrix ( ) of the graph
G is the in matrix defined as follows:
, ( , )
{
Such a matrix A, which contains entries of only 0 and 1, is called a bit matrix or a Boolean matrix.
//……………………………………………………………………………………….
The adjacency matrix A of the graph G does depend on the ordering of the nodes of G; that is, a
different ordering of the nodes may result in a different adjacency 'matrix. However, the matrices
resulting from two different orderings are closely related in that one can be obtained from the
there by simply interchanging rows and columns. Unless otherwise stated, we will assume that the
nodes of our graph G have a fixed ordering.
Suppose G is an undirected graph. Then the adjacency matrix A of G will be a symmetric matrix, i.e.,
one in which for every i and 1 . This follows from the fact that each undirected edge (u, v)
corresponds to the two directed edges (u, u) and (u. u).
The above matrix representation of a graph may he extended to multigraphs. Specifically. if G is a
multigraphs, then the adjacency matrix of G is the in x in matrix ( ) defined by setting a,
equal to the number of edges from .
Path Matrix:
Let G be a simple directed graph with m nodes, , , , … … . . .The path matrix or
reachability matrix of G is the m-square matrix ( ) defined as follows:
, ( , )
{
Suppose there is a path from , Then there must be a simple path from ,, when
, or there must be a cycle from , when ,. Since G has only m nodes, such a
simple path must have length − or less, or such a cycle must have length m or less This means
that there is a nonzero entry in the matrix defined at the end of the preceding subsection.
( )
Now find out , , , and from that make the path matrix and tell whether this is strongly
connected or not.
Answer:
Consider the graph G in Fig. 8-3. Suppose the nodes are stored in memory in a linear array DATA as
follows:
DATA: X, Y, Z, W
A=( )
Accordingly, in particular, there is a path of length 2 from to , there are two paths of length 3
from to , and there are three paths of length 4 from
Examining the matrix P. we see that the node is not reachable from any of the other nodes.
Recall that a directed graph G is said to be strongly connected if, for any pair of nodes u and v in G,
there are both a path from u to v and a path from v to u. Accordingly, G is strongly connected if and
only if the path matrix P of G has no zero entries. Thus the graph G in Fig. 8-3 is not strongly
Connected .
( )
Now find out , , , and from that make the path matrix and tell whether this is strongly
connected or not. Exam-2013
Answer:
Consider the graph G in Fig. 8-3. Suppose the nodes are stored in memory in a linear array DATA as
follows:
DATA: X, Y, Z, W
A=( )
( )
Now find out A2,A3,A4,B4 and from that make the path matrix and tell whether this is strongly
connected or not. Exam-2014
Question: Consider the following adjacency matrix below:
( )
Now find out A2,A3,A4,B4 and from that make the path matrix and tell whether this is strongly
connected or not. Exam-2015
Question: Consider the following adjacency matrix below:
( )
Now find out A2,A3,A4,B4 and from that make the path matrix and tell whether this is strongly
connected or not. Exam-2016
Question: Use the Warshall’s algorithm to find the shortest path matrix of the weighted matrix given
below?
Answer:
Applying the modified Wirshall's algorithm, we obtain the following matriccs Q0. Q1, Q,, Q3 and Q4
Q. To the right of cach matrix Q,, we show the matrix of paths which correspond to the lengths in
the matrix Q.
Question: Use the Warshall’s algorithm to find the shortest path matrix of the weighted matrix given
below. Exam-2016
( )
Consider the graph G in Fig. 8-7(a). The table in Fig. 8-7(b) shows each node in G followed by its
adjacency list, which is its list of adjacent nodes, also called its successors or neighbors. Figure 8-8
shows a schematic diagram of a linked representation of G in memory. specifically, the linked
representation will contain two lists (or tiles), a node list NODE and an edge list EDGE, as follows.
Here NODE will be the name or key value of the node, NEXT will be a pointer to the next node in the
list NODE and ADJ will be a pointer to the first clement in the adjacency list of the node, which is
maintained in the list EDGE. The shaded area indicates that there may be other information in the
record, such as the indegree INDEG of the node, the outdegree etc.
(b)Edge List:
Each element in the list EDGE will correspond to an edge of G and will be a record of
the form.
The field DEST will point to the location in the list NODE of the destination or terminal node of the
edge. The field LINK will link together the edges with the same initial node, that is, the nodes in the
same adjacency list. The shaded area indicates that there may be other information in the record
corresponding to the edge, such as a ficld.EDGE containing the labeled data of the edge when G is a
labeled graph, a field WEIGHT containing the weight of the edge when G is weighted graph, and
soon. We also need a pointer variable AVAILE for the list of available space in the list EDGE.
Figure 8-9 shows how the graph G in Fig. 8-7(a) may appear in memory. The choice of 10 locations
for the list NODE and 12 locations for the list EDGE is arbitrary.
Question: How many ways a Graph can be traversed? What is the significance of the STATUS field?
Exam-2014
Breadth-First Search(BFS)
Depth-First Search(DFS)
During the execution of our algorithms, each node N of G will be in one of three states, called the
status of N, as follows:
Breadth-First Search
In BFS First we examine the starting node A. Then we examine all the neighbors of
A. Then we examine all the neighbors of the neighbors of A. And so on. Naturally, we need to keep
track of the neighbors of a node, and we need to guarantee that no node is processed more than
once. This is accomplished by using a queue to hold nodes that are waiting to be processed, and by
using a field STATUS which tells us the current status of any node. The algorithm follows.
Algorithm A: This algorithm executes a breadth first search on a graph 0 beginning at a starting
node A.
1. Initialize all nodes to the ready state (STATUS 1). Put the starting node A in QUEUE
and change its status to the waiting state (STATUS = 2).
3. Repeat Steps 4 and 5 until QUEUE is empty:
4. Remove the front node N of QUEUE. Process N and change the status of N
to the processed state (STATUS = 3).
5. Add to the rear of QUEUE all the neighbors of N that arc in the steady state
(STATUS = 1), and change their status to the waiting state (STATUS = 2).
[End of Step 3 loop.]
6. Exit.
Depth-First Search:
The general idea behind a depth-first DFS beginning at a starting node A is as follows.
First we examine the starting node A. Then we examine each node N along a path P which begins at
A; that is, we process a neighbor of A. then a neighbor of a neighbor of A. and so on. After coming to a
"dead end," that is, to the end of the path P, we backtrack on P until we can continue along another
path .. The algorithm follows.
Algorithm : This algorithm executes a depth-first search on a graph G beginning at it starting node
Question: Consider the adjacency list of the graph G in the following table. Draw the graph and find
out the path from A to H with minimum number First Search. Exam-2015,2014
Question: Consider the adjacency list of the graph G in the following table. Find the nodes that are
reachable from node C using Depth first search. Exam-2016
Chap
ter 7
Symbol Tables
Important Question
1. What are the various hashing techniques ? Give suitable example. Exam-2013
2. How will you resolve the collisions, while inserting element into the hash table using
separate chaining method? Write the routine for inserting elements into a hash table using
the above mentioned technique. Exam-2013
Question: What are the various hashing techniques ? Give suitable example. Exam-2013
Answer:
Hashing:
The search time of each algorithm depends on the number n of elements in the collection
S of data. This section discusses a searching technique, called hashing or hash addressing, which is
essentially independent of the number n.
(a) !)ic,. ion ,,;ctijoI. Choose .a flu iii her in IalL dUln the n U riibct it of keys iii K. (The number in
is usually chosen to be a prime ii umber or a number without small divisors, s ince his
frequently minimizes the number of collisions.) The hash function II i ,, defined by 11(k) =
k (mod in) or 11(k) k (mud in) 4 1 I le ic k (mod ,n) denotes the remainder when k is
divided by in. The second formula is used when we want the hash addresses to range frort I
to in ra t her than from 0 to iii –
(b) Mia'suurc mci/run. ihie key A is squared. Then the hash function 11 is defined 1w 11(1<) = I
where / is Obtained by deleting 1.1 igi Is from both ends of k ' .We emphasize that the same
positions of k 2 must he used for all of the keys.
(b) loIdznç method. the key k is partitioned into a fiLl ill her of parts, k,, k, , where each part,
except possibly tire last, has the same number of digits as the required address. Then the
parts are added together, ignoring the last carry. That is, .................I-k,where the icar.ling-
digit carries. it any, are ignored. Sometimes, for extra ''milling, the even-numbered palls, k,,
k 1 ,.., a re each reversed before the addition
(c)
Question: How will you resolve the collisions,while inserting element into the hash table using
separate chaining method?Write the routine for inserting elements into a hash table using the above
mentioned technique. Exam-2013
Answer:
Suppose we want to add it record 1? with key k to our tile F, but suppose the memory location
address /1 1 A) is alread y occupied. This situation IS called coll,.cwn. This subsection discusses
two general ways of rcsolvi tig collisions. The particular procedure that one chooses depends on
many factors. f)uic important factor is the ratio of the number n of keys iii K (which is the number
of ecords in F) to the number in of hash addresses in L. This rati',, A = ps/ni. is called the load
factor.
First we show that collisions arc almost impossible to avoid. Specifically, suppose it class has 24
students and suppose the table has space for 365 records, One random hush function is to choose
the student's birthday as the hash address. Although the load factor A 24 / 365 7% is very small, it
can be shown that there is a better than fifty-filly chance that two of the students have the same hi t
h lay.
The efficiency of it hash function with it resolution iroceduie is measured by the average number of
prO/ic's (key comparisons) needed to hind the location of the record with a given key k. The
efficiency depends mainly oii the load factor A. Specifically, we are interested in the following two
quantities:
S( A) = average number of probes for it search
Chap
ter 8
Files
Important Question
He is working from 2016 at fiverr, freelancer.com, upwork as a content writer, technical writer,
educational writer, thesis proposal writer, Thesis paper writer, motivation letter writer, web
developer.
He was a Master Trainer of “Skills development for mobile game and application
project(SDMGAP)” project of ICT Ministry during 2018-19.
He also a Lecturer at Bangladesh Army University of Science and
Technology(BAUST)www.baust.edu.bd. Department of Computer Science and Engineering.
I participated several scientific and engineering conference in National and International
Level.
Email: [email protected];
https://www.facebook.com/abusalehmusa.miah