0% found this document useful (0 votes)
20 views70 pages

Final Lab Manual

The document is a lab manual for the Data Structures and Algorithms course at Sinhgad Academy of Engineering, outlining the vision and mission of the Computer Engineering department. It details program outcomes, specific outcomes, course objectives, and outcomes related to practical assignments involving data structures like hash tables, trees, and graphs. The manual emphasizes the importance of practical implementation and analysis of data structures in solving real-world problems.

Uploaded by

hetavimodi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views70 pages

Final Lab Manual

The document is a lab manual for the Data Structures and Algorithms course at Sinhgad Academy of Engineering, outlining the vision and mission of the Computer Engineering department. It details program outcomes, specific outcomes, course objectives, and outcomes related to practical assignments involving data structures like hash tables, trees, and graphs. The manual emphasizes the importance of practical implementation and analysis of data structures in solving real-world problems.

Uploaded by

hetavimodi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Sinhgad Academy of Engineering,Kondhwa(Bk),

Pune- 48

DEPARTMENTOF
COMPUTER
ENGINEERING

LAB MANUAL
PRACTICAL- DATA STRUCTURES AND ALGORITHMS LAB (210256)

S.E 2019 Pattern

Prepared by
Prof. Mrs. S. R.Dhotre

Prof. Mrs. S. S. Nalgirkar


Vision

उत्तमपुरुषान् उत्तमाभियं त्रृन् भ नमाातुं कटीबध्दः वयम् !

“We are committed to produce not only good


engineers but good humanbeings, also.”

Mission
“Holistic development of students and teachers is what we
believe in and work for. We strive to achieve this by imbibing
a unique value system, transparent work culture, excellent
academic and physical environment conducive to learning,
creativity and technology transfer. Our mandate is to
generate, preserve and share knowledge for developing a
vibrantsociety.”
Department of Computer Engineering

Vision

“To build the Department as a Centre of Excellence for students


in Computer Engineering.”

Mission
“We believe in developing value based system for student and
staff by providing healthy and transparent work culture to
cultivate new ideas in the field of engineering and technology
which will contribute to build a vibrant Society.”
Programme Outcomes (POs)

PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
PO2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences.
PO3. Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health and
safety, and the cultural, societal, and environmental considerations.
PO4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to provide
valid conclusions.
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modelling to complex engineering activities with an understanding of the
limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.
PO11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Program Specific Outcomes (PSOs)

Computer Engineering graduate will be able to,

PSO1: Project Development: Successfully complete hardware and/or software related system or application
projects, using the phases of project development life cycle to meet the requirements of service and product
industries; government projects; and automate other engineering stream projects.
PSO2: Domain Expertise: Demonstrate effective application of knowledge gained from different computer
domains like, data structures, data bases, operating systems, computer networks, security, parallel
programming, in project development, research and higher education.
PSO3: Career Development: Achieve successful Career and Entrepreneurship- The ability to employ modern computer
languages, environments, and platforms in creating innovative career paths to be an entrepreneur, and a zest for higher studies.
1. Graduate Attributes and Program Outcomes

Graduate Attributes Program Outcomes

a. An ability to apply knowledge of computing, mathematics, science,


1. Engineering
and engineering fundamentals appropriate to Computer
Knowledg Engineering.
e
b. An ability to define the problems and provide solutions by
2. Problem Analysis designing and conducting experiments, interpreting and analyzing
data.

3. Design & c. An ability to design, implement and evaluate a system, process,


Development component, and program to meet desired needs within realistic
of Solutions constraints.

4. Investigation of d. An ability to investigate, formulates, analyze, and provide


Complex Problem appropriate solution to the engineering problems.

5. Modern Tools e. An ability to use modern engineering tools and technologies


Usage necessary for engineering practices.

6. Engineer f. An ability to analyze the local and global impact of computing on


and individuals, organizations, and society.
Society
7. Environment g. An ability to understand the environmental issues and provide the
& sustainable system.
Sustainability
8. Ethics h. An ability to understand professional and ethical responsibility.

9. Individual i. An ability to function effectively as an individual or as a team


& member to accomplish the goal.
Teamwork
10.Communication j. An ability to communicate effectively at different levels.

11.Project k. An ability to understand engineering, management, financial


management aspects, performance, optimization, and time complexity necessary
& Finance for profession practice.
l. An ability to keep abreast with contemporary technologies through
12.Lifelong Learning
lifelong learning.
DATA STRUCTURES AND ALGORITHMS LAB (210256)

COURSE OBJECTIVES:

⮚ To understand practical implementation and usage of non-linear data structures


for solving problems of different domain.
⮚ To strengthen the ability to identify and apply the suitable data structure for the given
real-world problems.
⮚ To analyze advanced data structures including hash table, dictionary, trees, graphs,
sorting algorithms and file organization.

COURSE OUTCOMES:

CO1 Understand the ADT/libraries, hash tables and dictionary to


design algorithms for a specific problem.
CO2 Choose most appropriate data structures and apply algorithms for graphical
solutions of the problems.
CO3 Apply and analyze nonlinear data structures to solve real world complex
problems.
CO4 Apply and analyze algorithm design techniques for indexing, sorting, multi-
way searching, file organization and compression.
CO5 Analyze the efficiency of most appropriate data structure for creating efficient
solutions for engineering design situations.
LIST OF ASSIGNMENTS
Teaching Scheme Examination Scheme:
Practical: 4 hrs/week Term Work: 25
Marks Practical: 25
Marks
Software Required: Open Source Python, g++ / gcc compiler- / 64 bit Fedora, eclipse IDE

Sr.No Name of the assignment CO’s PO’s


Addres Addressed
s ed
1. Consider telephone book database of N clients. Make use of a
hash table implementation to quickly look up client‘s telephone
number. Make use of two collision handling techniques and CO1 a, b, c, d, e
compare them using number of comparisons required to find a set
of telephone numbers
2. Implement all the functions of a dictionary (ADT) using hashing
and handle collisions using chaining with / without replacement.
Data: Set of (key, value) pairs, Keys are mapped to values, Keys
must be comparable, Keys must be unique CO1 a, b, c, d, e
Standard Operations: Insert(key, value), Find(key), Delete(key)
3. A book consists of chapters, chapters consist of sections and
sections consist of subsections. Construct a tree and print the CO2, CO3
a, b, c, d, e
nodes. Find the time and space requirements of your method.
4. Beginning with an empty binary search tree, Construct binary
search tree by inserting the values in the order given. After
constructing a binary tree - i. Insert new node ii. Find number of
a, b, c, d, e
nodes in longest path from root iii. Minimum data value found CO2, CO3
in the tree iv. Change a tree so that the roles of the left and right
pointers are swapped at every node v. Search a value

5. Convert given binary tree into threaded binary tree.


CO1 a, b, c, d, e
Analyze time and space complexity of the algorithm.

6. There are flight paths between cities. If there is a flight between


city A and city B then there is an edge between the cities. The cost
of the edge can be the time that flight take to reach city B from A, CO2, CO3 a, b, c, d, e

or the amount of fuel used for the journey. Represent this as a


graph. The node can be represented by airport name or name of
the city. Use adjacency list representation of the graph or use
adjacency matrix representation of the graph. Check whether the
graph is connected or not. Justify the storage representation used.
7. You have a business with several offices; you want to lease
phone lines to connect them up with each other; and the phone
company charges different amounts of money to connect
different pairs of cities. You want a set of lines that connects CO4, CO5 a, b, c, d, e
all your offices with a minimum total cost. Solve the problem
by suggesting appropriate data structures.
8. A Dictionary stores keywords & its meanings. Provide facility
for adding new keywords, deleting keywords, updating values
of any entry. Provide facility to display whole data sorted in
ascending/ Descending order. Also find how many maximum CO1
a, b, c, d, e
comparisons may require for finding any keyword. Use Height
balance tree and find the complexity for finding a keyword

9. Implement the Heap/Shell sort algorithm implemented in Java


CO4, CO5 a, b, c, d, e
demonstrating heap/shell data structure with modularity of
programming language
10. Read the marks obtained by students of second year in an online
examination of particular subject. Find out maximum and a, b, c, d, e
minimum marks obtained in that subject. Use heap data CO4, CO5
structure.
Analyze the algorithm.
11. Department maintains a student information. The file contains
roll number, name, division and address. Allow user to add,
delete information of student. Display information of particular
employee. If record of student does not exist an appropriate
CO4, CO5 a, b, c, d, e
message is displayed. If it is, then the system displays the
student details. Use sequential file to main the data.

12. Company maintains employee information as employee ID,


name, designation and salary. Allow user to add, delete
information of employee. Display information of particular
CO4 a, b, c, d, e
employee. If employee does not exist an appropriate message is
displayed. If it is, then the system displays the employee details.
Use index sequential file to maintain the data.

13. Design a mini project to implement Snake and Ladders Game


a, b, c, d, e
using Python. CO4, CO5
ASSIGNMENT NO.1

Consider telephone book database of N clients. Make use of a hash table


implementation to quickly look up client‘s telephone number

Learning Objectives:

To understand concept of Hashing


To understand to find record quickly using hash function.
To understand different types of hashing.

Learning Outcome :
Learn python language.
Understand & implement concept of hash table.

Theory:

Hashing :
Hashing is the process of indexing and retrieving elements in a data structure to
provide faster way of finding the element using hash key.
OR

Hashing :- Store the elements as per the calculations of hashing(linear probing)


function.

hash(key) = key % size of the table

Hash Table :
Hash table is a data structure used for storing and retrieving data quickly. It stores data
is in an array format , where each data value has its own unique index. That’s why access
become quick if we know the index of the desired data.
Hash table uses array as an storage medium and every entry in the hash table is made
using Hash function.

Eg.,
Insert the keys = {46, 30, 33, 24, 28} in the hash table having the size of 5.

Hash table
H(46) = 46 % 5 = 1
0 30
H(30) = 30 % 5 = 0
1 46
H(33) = 33 % 5 = 3
2 28
H(24) = 24 % 5 = 4
3 33

4 24 H(28) = 28 % 5 = 3
Here, Bucket is not empty. So collision occurs . Therefore insert
The key at next empty bucket i.e. at index 2 .

Basic Operations

Following are the basic primary operations of a hash table.

Search − Searches an element in a hash table.


Insert − inserts an element in a hash table.
delete − Deletes an element from a hash table.

Hash Method:
Define a hashing method to compute the hash code of the key of the data item.

def hashFunction(self,element):
return element % self.size
Search Operation :

Whenever an element is to be searched, compute the hash code of the key


passed and locate the element using that hash code as index in the array. Use linear
probing to get the element ahead if the element is not found at the computed hash code.

Example :-
def search(self, record):
found = False
position = self.hashFunction(record.get_number())
self.comparisons += 1

if(self.table[position] != None):
if(self.table[position].get_name() == record.get_name() and
self.table[position].get_number() == record.get_number()):

isFound = True

print("Phone number found at position {} ".format(position) + " and total


comparisons are " + str(1))

return position

# if element is not found at position returned hash function


else:
position += 1

if position >= self.size-1:


position = 0

while self.table[position] != None or self.comparisons <= self.size:

if(self.table[position].get_name() == record.get_name() and


self.table[position].get_number() == record.get_number()):

isFound = True
i = self.comparisons + 1

print("Phone number found at position {} ".format(position) + " and total


comparisons are " + str(i) )

return position

else:
print("Record not found")
return False

position += 1
if position >= self.size-1:
position = 0
self.comparisons += 1

Insert Operation :
Whenever an element is to be inserted, compute the hash code of the key
passed and locate the index using that hash code as an index in the array. Use
linear probing for empty location, if an element is found at the computed hash code.

Example :
def insert(self, record):
# checking if the table is full

if self.isFull():
print("Hash Table Full")
return False
isStored = False
position = self.hashFunction(record.get_number())

# checking if the position is empty

if self.table[position] == None:
self.table[position] = record
print("Phone number of " + record.get_name() + " is at position " + str(position))
isStored = True

self.elementCount += 1
# collision occured hence we do linear probing
else:
print("Collision has occured for " + record.get_name() + "'s phone number at position "
+ str(position) + " finding new Position.")

while self.table[position] != None:


position += 1

if position >= self.size:


position = 0

self.table[position] = record

print("Phone number of " + record.get_name() + " is at position " + str(position))

isStored = True

self.elementCount += 1

return isStored

Delete Operation :
Whenever an element is to be deleted, compute the hash code of the key passed and locate
the index using that hash code as an index in the array. Use linear probing to get the element
ahead if an element is not found at the computed hash code. When found, store a dummy item there
to keep the performance of the hash table intact.

Collision :
Collision occurs when different keys hash to the same location in the hash table.
If collisions occur then it should be handled by applying some techniques, such
techniques are called collision handling techniques.
Collision
CollisionResolution Techniques
Resolution Techniques

Open/External Hashing Internal/Closed Hashing


OR OR
Closed Addressing Open Addressing

Separate chaining Linear Probing Quadratic Probing Double Hashing

With chaining with With chaining


Without chaining
replacement without replacement

Linear Probing :-
When collision occurs i.e. when two records demand for the same location in
the hash table, then the collision can be solved by placing second record linearly down
whenever the empty location is found.
Eg.,
Insert keys={37, 90, 45, 22, 17, 49, 55} in the table of size 10 using linear probing.

0 90 H(37) = 37 % 10 = 7
1 H(90) = 90 % 10 = 0
2 22 H(45) = 45 % 10 = 5
3 H(22) = 22 % 10 = 2
4 H(17) = 17 % 10 = 7 Here, collision occurs. Therefore insert the key 17
5 45 at next empty location i.e. at location 8.
6 55 H(49) = 49 % 10 = 9
7 37 H(55) = 55 % 10 = 5 Here, collision occurs. Therefore insert the key 55
8 17 at next empty location i.e. at location 6.
9 49
Double Hashing : -
Double hashing is a collision resolution technique used in hash tables. It works
by using two hash functions to compute two different hash values for a given key. The first
hash function is used to compute the initial hash value, and the second hash function is used
to compute the step size for the probing sequence.

There are two important rules to be followed for the second function :
1] It must never evaluate to zero.
2] Must make sure the all cells can be probed.

The formula to be used for double hashing is :


1] H1(key) = key % Table_Size
2] H2(key) = M - (key % M)
Where M is the prime number smaller than the size of the table.

Double hashing can be done using :


(H1(key)
(H1(key)++i *i *H2(key))
H2(key))%%Table_Size
Table_Size
Where i = 1 to m-1 (m=Table_Size)

Eg.,
Insert keys={37, 90, 45, 22, 17, 49, 55} in the table of size 10 using double hashing.

1] H1(37) = 37 % 10 = 7
0 90 2] H1(90) = 90 % 10 = 0
1 17 3] H1(45) = 45 % 10 = 5
2 22 4] H1(22) = 22 % 10 = 2
3
4 5] H1(17) = 17 % 10 = 7 …………….Collision occurs
5 45 H2=M-(key%M)………….M=prime number smaller than Table_size. Prime
6 55 number smaller than Table_Size 10 is 7. Hence ,M=7
7 37 H2(17) = 7-(17%7) = 4
8 [ H1(17)+H2(17) ] % 10 = 1
9 49
6] H1(49) = 49 % 10 = 9
7] H1(55) = 55 % 10 = 5 …………….Collision occurs
H2(55) = 7 - (55%7) = 1
[ H1(55)+H2(55) ] % 10 = 6
Expected Output: Menu driver output for inserting phone number, display and look up function.
e.g

Menu

Create Telephone book


Display
Look up

Conclusion : In this way we have implemented Hash table for quick lookup using python.
Assignment -2
Title:
Implement all the functions of a dictionary (ADT) using hashing.

Data: Set of (key, value) pairs, Keys are mapped to values, Keys must be
comparable, Keys must be unique

Standard Operations: Insert (key, value), Find(key), Delete(key)

Learning Objectives:
1. To understand Dictionary (ADT)
2. To understand concept of hashing
3. To understand concept & features like searching using hash function.

Learning Outcome:

1. Define class for Dictionary using Object Oriented features.


2. Analyze working of hash function.

Theory:

Dictionary ADT

Dictionary (map, association list) is a data structure, which is generally an


association of unique keys with some values. One may bind a value to a key, delete
a key (and naturally an associated value) and lookup for a value by the key. Values
are not required to be unique. Simple
usage example is an explanatory dictionary. In the example, words are keys and
explanations are values.

Dictionary Operations

 Dictionary create()
creates empty dictionary

 boolean isEmpty(Dictionary d)
tells whether the dictionary d is empty

 put(Dictionary d, Key k, Value v) 14


associates key k with a value v; if key k already presents in the dictionary old value is replaced
by v

 Value get(Dictionary d, Key k)


returns a value, associated with key kor null, if dictionary contains no such key

 remove(Dictionary d, Key k) removes key k

and associated value

 destroy(Dictionary d) destroys

dictionary d

Hash Table is a data structure which stores data in an associative manner. In a hash
table, data is stored in an array format, where each data value has its own unique index
value. Access of data becomes very fast if we know the index of the desired data.

Thus, it becomes a data structure in which insertion and search operations are very fast
irrespective of the size of the data. Hash Table uses an array as a storage medium and uses
hash technique to generate an index where an element is to be inserted or is to be located
from.

Hashing
Hashing is a technique to convert a range of key values into a range of indexes of an
array. We're going to use modulo operator to get a range of key values. Consider an
example of hash table of size 20, and the following items are to be stored. Item are in
the (key,value) format.

Basic Operations of hash table


Following are the basic primary operations of a hash table.

 Search − Searches an element in a hash table.

 Insert − inserts an element in a hash table.


 delete − Deletes an element from a hash table. 15
Search Operation :
Whenever an element is to be searched, compute the hash code of the key passed and
locate the element using that hash code as index in the array. Use linear probing to get the
element ahead if the element is not found at the computed hash code.

Example:
def search(key):
global size
hash_value = key % size

if hashtable[hash_value][0] == key:
print("KEY", key, "FOUND AT INDEX", hash_value)
else:
flag = 0
i=0
chain = hashtable[hash_value][1]

while hashtable[hash_value][0] is not None and hashtable[hash_value][0] % size != key % size:


hash_value = (key + i) % size
chain = hashtable[hash_value][1]

if hashtable[hash_value][0] == key:
print("KEY", key, "FOUND AT INDEX", hash_value)
chain = -1
flag = 1
break

i += 1

while chain != -1:


if hashtable[chain][0] == key:
print("KEY", key, "FOUND AT INDEX", chain)
flag = 1
break
chain = hashtable[chain][1]

if flag == 0:
print("KEY NOT FOUND")

Insert Operation :
Whenever an element is to be inserted, compute the hash code of the key passed and
locate the index using that hash code as an index in the array. Use linear probing for empty
location, if an element is found at the computed hash code.

Example:
def insert(key):
global size, total
hash_value = key % size
if hashtable[hash_value][0] is None:
hashtable[hash_value][0] = key
bucket[key % size] = hash_value
else:
flag = 0
for i in range(0, size):
hash_value = (key + i) % size

if hashtable[hash_value][0] is None:
total += 1
flag = 1

if bucket[key % size] != 1:
hashtable[bucket[key % size]][1] = hash_value
bucket[key % size] = hash_value
hashtable[hash_value][0] = key
break

if flag == 0:
print("KEY", key, "NOT INSERTED AS HASH TABLE IS FULL")

Delete Operation :
Whenever an element is to be deleted, compute the hash code of the key passed and
locate the index using that hash code as an index in the array. Use linear probing to get the
element ahead if an element is not found at the computed hash code. When found, store a
dummy item there to keep the performance of the hash table intact.

Example:
def delete(key):
global size
hash_value = key % size

if hashtable[hash_value][0] == key:
hashtable[hash_value][0], hashtable[hash_value][1] = None, -1
print("KEY", key, "WAS DELETED FROM INDEX", hash_value)
else:
flag = 0
i=0
chain1 = hash_value
chain2 = hashtable[hash_value][1]

while hashtable[hash_value][0] is not None and hashtable[hash_value][0] % size != key % size:


hash_value = (key + i) % size
chain1 = chain2
chain2 = hashtable[hash_value][1]

if hashtable[hash_value][0] == key:
hashtable[chain1][1] = hashtable[chain2][1]
hashtable[chain2][0], hashtable[chain2][1] = None, -1
print("KEY", key, "WAS DELETED FROM INDEX", chain2)
chain2 = -1
flag = 1
break

i += 1
while chain2 != -1:
if hashtable[chain2][0] == key:
hashtable[chain1][1] = hashtable[chain2][1]
hashtable[chain2][0], hashtable[chain2][1] = None, -chain1
print("KEY", key, "DELETED FROM INDEX", chain2)
flag = 1
break
chain1 = chain2
chain2 = hashtable[chain2][1]

if flag == 0:
print("KEY NOT FOUND")

Collision :
Collision occurs when different keys hash to the same location in the hash table.
If collisions occur then it should be handled by applying some techniques, such
techniques are called collision handling techniques.

Collision
Collision Resolution Techniques
Resolution Techniques

Open/External Hashing Internal/Closed Hashing


OR OR
Closed Addressing Open Addressing

Separate chaining Linear Probing Quadratic Probing Double Hashing

With chaining with With chaining


Without chaining
replacement without replacement

Linear probing with chaining without replacement :-


In collision handling method chaining is a concept which introduces an additional
field with data i.e. chain. A separate chain table is maintained for colliding data. When
collision occurs, we store the second colliding data by linear probing method. The address of
this colliding data can be stored with the first colliding element in the chain table, without
replacement.

Example:
Keys={ 19, 34, 25, 48, 7, 14 } Table Size = 6
Construct the hash table using linear probing with chaining without replacement.
Index Keys Chain 1) H(19) = 19 % 6 = 1
0 48 -1 2) H(34) = 34 % 6 = 4
1 19 2 3) H(25) = 25 % 6 = 1 Here, collision occurs. Therefore insert
2 25 3 the key 25 at next empty location i.e. at
2 & adjust chain table.
3 7 -1
4) H(48) = 48 % 6 = 0
4 34 -1
5) H(7) = 7 % 6 = 1 Here, collision occurs. Therefore insert
5 14 -1
the key 7 at next empty location i.e. at
3 & adjust chain table.

6) H(14)= 14 % 6 = 2 Here, collision occurs. Therefore insert


the key 14 at next empty location i.e. at
5 & adjust chain table.
Keys 19 34 25 48 7 14
No. of
comparisons 1 1 2 1 3 4
Total No. of comparisons = ( Element count) * (No. of comparisons)

= (3*1) + (1*2) + (1*3) + (1*4)


= 12

Average No. of comparisons = Total No. of comparisons


Total No. of buckets

= 12
6

= 2

Linear probing with chaining with replacement :-


In this technique , we replace the actual element to its belonging position. If the
position of the element is occupied by an element which does not belong to that correspond-
-ing location then we make replacement.

Example:
Keys={ 19, 34, 25, 48, 7, 14 } Table Size = 6
Construct the hash table using linear probing with chaining without replacement.

Index Keys Chain


0 48 -1 1) H(19) = 19 % 6 = 1
1 19 5 2) H(34) = 34 % 6 = 4
2 14 -1 3) H(25) = 25 % 6 = 1 Here, collision occurs. Therefore insert
the key 25 at next empty location i.e. at
3 7 -1
2 & adjust chain table.
4 34 -1
4) H(48) = 48 % 6 = 0
5 25 3
5) H(7) = 7 % 6 = 1 Here, collision occurs. Therefore insert
the key 7 at next empty location i.e. at
3 & adjust chain table.
6) H(14)= 14 % 6 = 2 So, insert 14 at index 2 but at index 2 key
25 is stored which does not belong to
index 2.
Hence replace 25 by 14 & place 25 at next
empty location.
After insertion of 14, adjust the chain table.

Keys 19 34 25 48 7 14
No. of
comparisons 1 1 5 1 3 7

Total No. of comparisons = ( Element count) * (No. of comparisons)

= (3*1) + (1*5) + (1*3) + (1*7)


= 18

Average No. of comparisons = Total No. of comparisons


Total No. of buckets

= 18
6

= 3

Expected Output: Create dictionary using hash table and search the elements in table.

Conclusion: This program gives us the knowledge of dictionary (ADT).


Assignment -3

Title:
A book consists of chapters, chapters consist of sections and sections consist of subsections.
Construct a tree and print the nodes. Find the time and space requirements of your method.

Learning Objectives:
✓ To understand concept of class
✓ To understand concept & features of object-oriented programming.
✓ To understand concept of tree data structure.

Learning Outcome:
• Define class for structures using Object Oriented features.
• Analyze tree data structure.

Theory:
Introduction to Tree:

Definition:
A tree T is a set of nodes storing elements such that the nodes have a parent-child relationship
that satisfies the following.
• If T is not empty, T has a special node called the root that has no parent.
• Each node v of T different than the root has a unique parent node w; each node with parent w is
a child of w.

Recursive definition
• T is either empty.
• or consists of a node r (the root) and a possibly empty set of trees whose roots are the children
of r.

Tree is a widely used data structure that emulates a tree structure with a set of linked
nodes. The tree graphicaly is represented most commonly as on Picture 1. The circles are the
nodes, and the edges are the links between them.

1
Trees are usually used to store and represent data in some hierarchical order. The data are stored
in the nodes, from which the tree is consisted of.

Each node in a tree has zero or more child nodes, which are one level lower in the tree
hierarchy (by convention, trees grow down, not up as they do in nature). A node that has a child is called
the child's parent node (or ancestor node, or superior). A node has at most one parent. A node that has no
children is called a leaf, and that node is of course at the bottom most level of the tree. The height of a
node is the length of the longest path to a leaf from that node. The height of the root is the height of the
tree. In other words, the "height" of tree is the "number of levels" in the tree. Or more formally, the height
of a tree is defined as follows:

1. The height of a tree with no elements is 0


2. The height of a tree with 1 element is 1
3. The height of a tree with > 1 element is equal to 1 + the height of its tallest subtree.

The depth of a node is the length of the path to its root (i.e., its root path). Every child node is
always one level lower than his parent.
The topmost node in a tree is called the root node. Being the topmost node, the root node will
not have parents. It is the node at which operations on the tree commonly begin (although some
algorithms begin with the leaf nodes and work up ending at the root). All other nodes can be reached
from it by following edges or links. (In the formal definition, a path from a root to a node, for each
different node is always unique). In diagrams, it is typically drawn at the top.
In some trees, such as heaps, the root node has special properties.
A subtree is a portion of a tree data structure that can be viewed as a complete tree in itself. Any
node in a tree T, together with all the nodes below his height, that are reachable from the node,
comprise a subtree of T.

Fig1. An example of a tree

An internal node or inner node is any node of a tree that has child nodes and is thus not a leaf
node.

2
Important Terms
Following are the important terms with respect to tree.

• Path − Path refers to the sequence of nodes along the edges of a tree.
• Root − The node at the top of the tree is called root. There is only one root per tree and
one path from the root node to any node.
• Parent − Any node except the root node has one edge upward to a node called parent.
• Child − The node below a given node connected by its edge downward is called its child node.
• Leaf − The node which does not have any child node is called the leaf node.
• Subtree − Subtree represents the descendants of a node.
• Visiting − Visiting refers to checking the value of a node when control is on the node.
• Traversing − Traversing means passing through nodes in a specific order.
• Levels − Level of a node represents the generation of a node. If the root node is at level 0,
then its next child node is at level 1, its grand child is at level 2, and so on.
• keys − Key represents a value of a node based on which a search operation is to be
carried out for a node.

Advantages of trees
Trees are so useful and frequently used because they have some very serious advantages:

• Trees reflect structural relationships in the data.


• Trees are used to represent hierarchies.
• Trees provide an efficient insertion and searching.
• Trees are very flexible data, allowing to move subtrees around with minimum effort

For this assignment we are considering the tree as follows:

3
Expected Output: Formation of tree structure for book and its sections.

Conclusion: This program gives us the knowledge tree data structure.

4
Assignment –4
Title:
Beginning with an empty binary search tree, Construct binary searchtree by inserting the values
in the order given. After constructing a binary tree –
i. Insert new node
ii. Find number of nodes in longest path
iii. Minimum data value found in the tree
iv. Change a tree so that the roles of the left and right pointers are swapped atevery node
v. Search a value

Learning Objective:

✓ To understand the basic concept of Non- L i n e a r Data Structure.


✓ “TREE” and its basicoperation in Data structure.

Learning Outcome:

✓ To implement the basic concept of Binary Search Tree to store a number in it.
✓ To perform basic Operation Insert, Delete and search, Traverse in tree in Data structure.

Theory –
Tree represents the nodes connected by edges. Binary Tree is a special data structure used for data
storage purposes. A binary tree has a special condition that each node can have a maximum of two
children. A binary tree has the benefits of both an ordered array and a linked list as search is as
quickas in a sorted array and insertion or deletion operation are as fast as in linked list.

Binary Search Tree Representation

Binary Search tree exhibits a special behavior. A node's left child must have a value less than its
parent's value and the node's right child must have a value greater than its parent value.

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
properties −
• The left sub-tree of a node has a key less than to its parent node's key.
• The right sub-tree of a node has a key greater than to its parent node's key.
Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree
and can be defined as –

left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)

5
Tree Node
Following Structure is used for Node creation
Struct node
{Int data ;
Struct node *leftChild;
Struct node *rightChild;
};

Fig: Binary Search Tree

BST Basic Operations


The basic operations that can be performed on a binary search tree data structure, are the
following −
1. Insert− Inserts an element in a tree/create a tree.
2. Search− Searches an element in a tree.
3. Traversal− A traversal is a systematic way to visit all nodes of T -Inorder, Preprder, Postorder.
4. Delete: Delete a node from tree.

1. Insert Operation: Algorithm

6
2. Search Operation:Algorithm

3. Tree Traversal
A.In order traversal algorithm

B. Pre order traversal Algorithm

C. Post order traversal Algorithm

7
3. Deleting in a BST

case 1: Delete a node with zero child-


if
x is left of its parent,
set parent(x).left= null
else
set parent(x).right = null
case 2: Delete a node with one child
link parent(x) to the child of x.
case 3: Delete a node with 2 children
Replace inorder successor to deleted node position.

Expected Output:

Formation of binary search tree structure with its basic Operation Insert, Delete and search, Traverse in
tree.

Conclusion: This program gives us the knowledge binary search tree data structure and its basic
operations.

8
9
Assignment -5

Title:
Convert given binary tree into threaded binary tree. Analyze time and space complexity of the
algorithm.

Learning Objective:

To understand the basic concept of Non-Linear Data Structure “threaded binary tree” and its use
in Data structure.

Learning Outcome:

To convert the Binary Tree into threaded binary tree and analyze its time and space complexity.

Theory –

Threaded Binary Tree

Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and
withoutrecursion.
In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a
right pointer is NULL, it is used to store inorder successor.
Inorder traversal of a Binary treeis either be done using recursion or with the use of a auxiliarystack.

Node Structure in Threaded Binary Tree :-


L bit L link Data R link R bit
1) L bit and R bit are either 0 or 1.
2) If L bit is 1 means there is a left child and if 0 means there is no left child.
3) If R bit is 1 means there is a right child and if 0 means there is no right child.
4) L link points to left child node and R link points right child node.
5) Data is the actual element or the value.
Representation of a Threaded Node :
Following is C++ Representation of a double threaded node.

struct Node
{
int data;
Node *left, *right;
bool lbit, rbit;
}

There are two types of Threaded Binary Tree :

1) Single Threaded:
Where a NULL right pointer is made to point to the inorder successorFollowing diagram shows an
example Single Threaded Binary Tree. The dotted lines represent threads.

Inorder Traversal = 4 2 5 1 6 3 7
1 -999 0

1 1 0

1 3 1
1 2 1

0 4 0 0 5 0 0 6 0 0 7 0

2 ) Double Threaded:
Where both left and right NULL pointers are made to point to inorder predecessor and inorder
successor, respectively. The predecessor threads are useful for reverse inorder traversal and
postorder traversal.
The threads are also useful for fast accessing ancestors of a node.

1 -999 0

1 1 0

1 3 1
1 2 1

0 4 0 0 5 0 0 6 0 0 7 0
Conversion of Binary Tree to Threaded Binary Tree

Initialize pointers: Traverse the binary tree in-order, and for each node, if its left child is null, make it point
to the predecessor (the previous node in in-order traversal). Similarly, if the right child is null, make it point
to the successor (the next node in in-order traversal).
Threading process:While traversing in-order, if the left child of a node is null, link it to its in-order
predecessor. If the right child is null, link it to its in-order successor.
Final threading: Finally, make the left pointer of the leftmost node point to the in-order predecessor that is
dummy node, and make the right pointer of the rightmost node point to the in-order successor that is dummy
node.

Time Complexity Analysis:

● Traversing the binary tree to thread the nodes takes O(n) time, where n is the number of nodes in the tree.
● Finding the leftmost and rightmost nodes takes O(n) time in total.
● Overall, the time complexity of the algorithm is O(n).

Space Complexity Analysis:

● The space complexity primarily depends on the recursion stack during in-order traversal, which could be
O(h), where h is the height of the tree. In the worst case (for skewed trees), it could be O(n).
● Additionally, the algorithm uses a constant amount of extra space for auxiliary variables.
● Thus, the overall space complexity is O(n).

Expected Outcome:
The binary tree into threaded binary tree in one single traversal with no extra space required.

Conclusion: Able to convert the Binary Tree into threaded binary tree and analyze its time and
space complexity.
Assignment -6

Title:
There are flight paths between cities. If there is a flight
between city A and city B then
there is an edge between the cities. The cost of the edge can be the time that flight take to reach
city B from A, or the amount of fuel used for the journey. Represent this as a graph. The node
can be represented by airport name or name of the city. Use adjacency list representation of the
graph or use adjacency matrix representation of the graph. Justify the storage representation
used.

Learning Objectives:

To understand concept of Graph data structure

To understand concept of representation of graph.

Learning Outcome:
Define class for graph using Object Oriented
features. Analyze working of functions.

Theory:

Graphs are the most general data structure. They are also commonly used data structures.

Graph definitions:
A non-linear data structure consisting of nodes and links between nodes.

Undirected graph definition:


An undirected graph is a set of nodes and a set of links between the nodes.

Each node is called a vertex, each link is called an edge, and each edge connects two
vertices.

The order of the two connected vertices is unimportant.

An undirected graph is a finite set of vertices together with a finite set of edges. Both sets
might be empty, which is called the empty graph.
Graph Implementation:
Different kinds of graphs require different kinds of implementations, but the fundamental
concepts of all graph implementations are similar. We'll look at several representations for one
particular kind of graph: directed graphs in which loops are allowed.

Representing Graphs with an Adjacency Matrix

Fig: Graph and adjacency matrix

Definition:

An adjacency matrix is a square grid of true/false values that represent the edges of a
graph.

If the graph contains n vertices, then the grid contains n rows and n columns.

For two vertex numbers i and j, the component at row i and column j is true if there is
an edge from vertex i to vertex j; otherwise, the component is false.

Once the adjacency matrix has been set, an application can examine locations of the matrix
to determine which edges are present and which are missing.
Representing Graphs with Edge Lists

Fig: Graph and adjacency list for each node

Definition:

A directed graph with n vertices can be represented by n different linked

lists. List number i provides the connections for vertex i.

For each entry j in list number i, there is an edge from i to j.

Loops and multiple edges could be allowed.

Representing Graphs with Edge Sets

To represent a graph with n vertices, we can declare an array of n sets of integers.

Expected Output: Create Adjacency matrix to represent path between various cities.

Conclusion: This program gives us the knowledge of adjacency matrix graph.


Assignment -7

Title:

You have a business with several offices; you want to lease phone lines to connect them
up with each other; and the phone company charges different amounts of money to connect
different pairs of cities. You want a set of lines that connects all your offices with a minimum
total cost. Solve the problem by suggesting appropriate data structures.

Learning Objective:

To understand the concept and basic of spanning.


To understand Graph in Data structure.

Learning Outcome:
To implement the spanning
To find the minimum distancebetween the vertices of Graph in Data structure.

Theory
Properties of a Greedy Algorithm:

At each step, the best possible choice is taken and after that only the sub-problem is
solved.

Greedy algorithm might be depending on many choices. But it cannot ever be


depending upon any choices of future and neither on sub-problems solutions.

The method of greedy algorithm starts with a top and goes down, creating greedy
choices in a series and then reduce each of the given problem to even smaller ones.

Minimum Spanning Tree:


A Minimum Spanning Tree (MST) is a kind of a sub graph of an undirected graph in which,
the sub graph spans or includes all the nodes has a minimum total edge weight.

To solve the problem by a prim's algorithm, all we need is to find a spanning tree of minimum
length, where a spanning tree is a tree that connects all the vertices together and a minimum
spanning tree is a spanning tree of minimum length.

Properties of Prim's Algorithm:


Prim's Algorithm has the following properties:

1 It grows the tree until it spans all the vertices of the graph.
2 An edge is added to the tree, at every step, that crosses a cut if its weight is the
minimum of any edge crossing the cut, connecting it to a vertex of the graph.

Algorithm:

Write Prim’s Algorithm Here


Example: Explain any one example with all steps

Conclusion: Understood the concept and basic of spanning and to find the minimum distance between
thevertices of Graph in Data structure.
Assignment -8
Title:
A Dictionary stores keywords & its meaning. Provide facility for adding new keywords, deleting
keywords, updating values of any entry. Provide facility to display whole data sorted in ascending/
Descending order. Also find how many maximum comparisons may require for finding any keyword.
Use Height balance tree and find the complexity for finding a keyword.

Learning Objectives:

✔ To understand concept of height balanced tree data structure.


✔ To understand procedure to create height balanced tree.

Learning Outcome:

Define class for AVL using Object Oriented features.


Analyze working of various operations on AVL
Tree.

Theory:
An empty tree is height balanced tree if T is a nonempty binary tree with TL and
TR asits left and right sub trees. The T is height balance if and only if Its balance factor is
0, 1, -1.

AVL (Adelson- Velskii and Landis) Tree: A balance binary search tree. The best
search time, that is O (log N) search times. An AVL tree is defined to be a well-balanced
binary search tree in which each of its nodes has the AVL property. The AVL property is
that the heights of the left and right sub-trees of a node are either equal or if they differ only
by 1.
It is observed that BST's worst-case performance is closest to linear search
algorithms, that is Ο(n). In real-time data, we cannot predict data pattern and their
frequencies. So, a need arises to balance out the existing BST.

Named after their inventor Adelson, Velski & Landis, AVL trees are height
balancing binary search tree. AVL tree checks the height of the left and the right sub-trees
and assures that the difference is not more than 1. This difference is called the Balance
Factor.

Here we see that the first tree is balanced and the next two trees are not balanced −

In the second tree, the left subtree of C has height 2 and the right subtree has height
0, so the difference is 2. In the third tree, the right subtree of A has height 2 and the left is
missing, soit is 0, and the difference is 2 again. AVL tree permits difference (balance factor)
to be only 1.

BalanceFactor = height(left-sutree) − height(right-sutree)

If the difference in the height of left and right sub-trees is more than 1, the tree is balanced
usingsome rotation techniques.

AVL Rotations
To balance itself, an AVL tree may perform the following four kinds of rotations −

Left rotation

Right rotation
Left-Rightrotation
Right-Leftrotation

The first two rotations are single rotations, and the next two rotations are double
rotations. To have an unbalanced tree, we at least need a tree of height 2. With this simple
tree, let's understand them one by one.
Left Rotation

If a tree becomes unbalanced, when a node is inserted into the right subtree of the
rightsubtree, then we perform a single left rotation −

In our example, node A has become unbalanced as a node is inserted in the right
subtreeof A's right subtree. We perform the left rotation by making A the left-subtree of B.

Right Rotation

AVL tree may become unbalanced, if a node is inserted in the left subtree of the
leftsubtree. The tree then needs a right rotation.

As depicted, the unbalanced node becomes the right child of its left child by performing a
rightrotation.

Left-Right Rotation

Double rotations are slightly complex version of already explained versions of


rotations. To understand them better, we should take note of each action performed while
rotation. Let's first check how to perform Left-Right rotation. A left-right rotation is a
combination of left rotation followed by right rotation.
State Action

A node has been inserted into the right subtree of the left subtree.
This makes C an unbalanced node. These scenarios cause AVL tree
to perform left-right rotation.

We first perform the left rotation on the left subtree of C. This


makes A, the left subtree of B.

Node C is still unbalanced, however now, it is because of


the left- subtree of the left-subtree.

We shall now right rotate the tree, making B the new root node
of this subtree. C now becomes the right subtree of its own left
subtree.

The tree is now balanced.


Right-Left Rotation

The second type of double rotation is Right-Left Rotation. It is a combination of right


rotation followed by left rotation.

State Action

A node has been inserted into the left subtree of the right subtree.
This makes A, an unbalanced node with balance factor 2.

First, we perform the right rotation along C node, making C the


right subtree of its own left subtree B. Now, B becomes the right
subtree of A.

Node A is still unbalanced because of the right subtree of its right


subtree and requires a left rotation.

A left rotation is performed by making B the new root node of the


subtree. A becomes the left subtree of its right subtree B.

The tree is now balanced.

41
Algorithm AVL TREE:
Insert:-

Write Algorithm here

Expected Output: Allow Add, delete operations on dictionary and also display data in sorted order.

Conclusion: This program gives us the knowledge height balanced binary tree.
Assignment -9

Title:
Implement the Heap/Shell sort algorithm implemented in Java demonstrating heap/shell data
structure with modularity of programming language .
Learning Objectives:
 To understand concept of heap in data structure.
 To understand concept & features of java language.

Learning Outcome:
 Define class for heap using Object Oriented features.
 Analyze working of heap sort .

Theory:

Heap Sort:

Heap sort is a comparison-based sorting technique based on Binary Heap data


structure. Itis similar to selection sort where we first find the maximum element and place the
maximum element at the end. We repeat the same process for remaining element.

What is Binary Heap?

Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in
which every level, except possibly the last, is completely filled, and all nodes are as far left
as possible (Source Wikipedia)

A Binary Heap is a Complete Binary Tree where items are stored in a special order
such that value in a parent node is greater (or smaller) than the values in its two children
nodes. The former is called as max heap and the latter is called min heap. The heap can be
represented by binary tree or array.
Why array-based representation for Binary Heap?

Since a Binary Heap is a Complete Binary Tree, it can be easily represented as array
and array based representation is space efficient. If the parent node is stored at index I, the
left child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing
starts at 0).

44
Heap Sort Algorithm for sorting in increasing order:

1. Build a max heap from the input data.

2. At this point, the largest item is stored at the root of the heap. Replace it with the last
item ofthe heap followed by reducing the size of heap by 1. Finally, heapify the root of
tree.
3. Repeat above steps until size of heap is greater than 1.

How to build the heap?

Heapify procedure can be applied to a node only if its children nodes are heapified.
Sothe heapification must be performed in the bottom up order.

Lets understand with the help of an example:

Input data: 4, 10, 3, 5, 1

The numbers in bracket represent the indices in the


arrayrepresentation of data.

Applying heapify procedure to index 1:

Applying heapify procedure to index 0:

The heapify procedure calls itself recursively to build heapin top-down manner.

45
Algorithm:

STEP 1: Logically, think the given array as Complete Binary Tree,


STEP 2: For sorting the array in ascending order, check whether the tree is satisfying Max-
heap property at each node, (For descending order, Check whether the tree is
satisfying Min-heap property) Here we will be sorting in Ascending order,
STEP 3: If the tree is satisfying Max-heap property, then largest item is stored at the root of
the heap. (At this point we have found the largest element in array, Now if we
place this element at the end(nth position) of the array then 1 item in array is at
proper place.)

We will remove the largest element from the heap and put at its proper place(nth
position) in array.
After removing the largest element, which element will take its place? We will put
last element of the heap at the vacant place. After placing the last element at the root, The
new tree formed may or may not satisfy max-heap property. So, If it is not satisfying max-
heap property then first task is to make changes to the tree, So that it satisfies max-heap
property.
(Heapify process: The process of making changes to tree so that it satisfies max-heap
property is called heapify)
When tree satisfies max-heap property, again largest item is stored at the root of the
heap. We will remove the largest element from the heap and put at its proper place(n-1
position) in array. Repeat step 3 until size of array is 1 (At this point all elements are sorted.)

Expected Output: Elements in sorted order.

Conclusion: This program gives us the knowledge of heap data structure.

46
Assignment-10

Title:
Read the marks obtained by students of second year in an online examination of particular subject.
Find out maximum and minimum marks obtained in a that subject. Use heap data structure. Analyze
the algorithm.

Learning Objectives:

 To understand concept of heap


 To understand concept & features like max heap, min heap.

Learning Outcome:

 Define class for heap using Object Oriented features.


 Analyze working of functions.

Theory:
Heap is a special case of balanced binary tree data structure where the root-node
key iscompared with its children and arranged accordingly. If α has child node β then –

key(α) ≥ key(β)

As the value of parent is greater than that of child, this property generates Max Heap.
Based on this criterion, a heap can be of two types −

For Input → 35 33 42 10 14 19 27 44 26 3126 31

Min-Heap − Where the value of the root node is less than or equal to either of its children.

47
Max-Heap − Where the value of the root node is greater than or equal to either of its children.

Both trees are constructed using the same input and order of arrival.

Max Heap Construction Algorithm


We shall use the same example to demonstrate how a Max Heap is created. The
procedure to create Min Heap is similar but we go for min values instead of max values.
We are going to derive an algorithm for max heap by inserting one element at a time.
At any point of time, heap must maintain its property. While insertion, we also assume that
we are inserting a node in an already heapified tree.

Step 1 − Create a new node at the end of heap.


Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

Note − In Min Heap construction algorithm, we expect the value of the parent node to be
lessthan that of the child node.
Let's understand Max Heap construction by an animated illustration. We consider the same
inputsample that we used earlier.

INPUT:35,33,42,10,14,19,27,44,16,31

Max Heap Deletion Algorithm


Let us derive an algorithm to delete from max heap. Deletion in Max (or Min) Heap
alwayshappens at the root to remove the Maximum (or minimum) value.

48
Step 1 − Remove root node.
Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its
parent.Step 4 − If value of parent is less than child, then
swap them. Step 5 − Repeat step 3 & 4 until Heap
property holds.

Expected Output: Find min and max marks obtained.

Conclusion: This program gives us the knowledge of heap and its types.

49
Assignment-11

Title:
Department maintains a student information. The file contains roll number, name, division and
address. Allow user to add, delete information of student. Display information of particular employee.
If record of student does not exist an appropriate message is displayed. If it is, then the system
displays the student details. Use sequential file to main the data.

Learning Objectives:

 To understand concept of file organization in data structure.


 To understand concept & features of sequential file organization.

Learning Outcome:
 Define class for sequential file using Object Oriented features.
 Analyze working of various operations on sequential file.

Theory:
File organization refers to the relationship of the key of the record to the physical location
of that record in the computer file. File organization may be either physical file or a logical file.
A physical file is a physical unit, such as magnetic tape or a disk. A logical file on the other hand
is a complete set of records for a specific application or purpose. A logical file may occupy a part
of physical file or may extend over more than one physical file.

There are various methods of file organizations. These methods may be efficient for
certain types of access/selection meanwhile it will turn inefficient for other selections. Hence it is
up to the programmer to decide the best suited file organization method depending on his
requirement.

Some of the file organizations are:

1. Sequential File Organization Heap


2. File Organization
3. Hash/Direct File Organization
4. Indexed Sequential Access Method
5. B+ Tree File Organization
6. Cluster File Organization

50
Sequential File Organization:
It is one of the simple methods of file organization. Here each file/records are stored one
after the other in a sequential manner. This can be achieved in two ways:

 Records are stored one after the other as they are inserted into the tables. This method is called
pile file method. When a new record is inserted, it is placed at the end of the file.In the case of
any modification or deletion of record, the record will be searched in the memory blocks. Once it
is found, it will be marked for deleting and new block of recordis entered.

Inserting a new record:

In the diagram above, R1, R2, R3 etc are the records. They contain all the attribute of a
row. i.e.; when we say student record, it will have his id, name, address, course, DOB etc.
Similarly R1, R2, R3 etc can be considered as one full set of attributes.

In the second method, records are sorted (either ascending or descending) each
time they are inserted into the system. This method is called sorted file method. Sorting of records
may bebased on the primary key or on any other columns. Whenever a new record is inserted, it will be
inserted at the end of the file and then it will sort – ascending or descending based on key value and
placed at the correct position. In the case of update, it will update the record and then sort thefile to
place the updated record in the right place. Same is the case with delete.

51
Inserting a new record:

Advantages:

 Simple to understand.
 Easy to maintain and organize
 Loading a record requires only the record key.
 Relatively inexpensive I/O media and devices can be used.
 Easy to reconstruct the files.
 The proportion of file records to be processed is high.

Disadvantages:

 Entire file must be processed, to get specific information.


 Very low activity rate stored.
 Transactions must be stored and placed in sequence prior to processing.
 Data redundancy is high, as same data can be stored at different places with
differentkeys.
 Impossible to handle random enquiries.

Expected Output: If record of student does not exist an appropriate message is displayed
otherwise thestudent details are displayed.

Conclusion: This program gives us the knowledge sequential file organization.

52
Assignment-12

Title:

Company maintains employee information as employee ID, name, designation, and salary.
Allow user to add, delete information of employee. Display information of particular
employee. If employee does not exist an appropriate message is displayed. If it is, then the system
displays the employee details. Use index sequential file to maintain the data.

Learning Objectives:

 To understand concept of file organization in data structure.


 To understand concept & features of Indexed Sequential file organization.

Learning Outcome:

 Define class for sequential file using Object Oriented features.


 Analyze working of various operations on Indexed Sequential Access Method

Theory:
File organization refers to the relationship of the key of the record to the physical location
of that record in the computer file. File organization may be either physical file or a logical file.
A physical file is a physical unit, such as magnetic tape or a disk. A logical file on the other hand
is a complete set of records for a specific application or purpose. A logical file may occupy a part
of physical file or may extend over more than one physical file.

There are various methods of file organizations. These methods may be efficient for
certain types of access/selection meanwhile it will turn inefficient for other selections. Hence it is
up to the programmer to decide the best suited file organization method depending on his
requirement.

Some of the file organizations are

1. Sequential File Organization Heap File Organization


2. Hash/Direct File Organization
3. Indexed Sequential Access Method
4. B+ Tree File Organization
5. Cluster File Organization

53
Indexed sequential access method (ISAM)

ISAM method is an advanced sequential file organization. In this method, records are stored in
the file using the primary key. An index value is generated for each primary key and mapped
with the record. This index contains the address of the record in the file.

If any record has to be retrieved based on its index value, then the address of the data block is fetched and the
record is retrieved from the memory.

Pros of ISAM:

 In this method, each record has the address of its data block, searching a record in a huge
database is quick and easy.
 This method supports range retrieval and partial retrieval of records. Since the index is based
on the primary key values, we can retrieve the data for the given range of value. In the same
way, the partial value can also be easily searched, i.e., the student name starting with 'JA' can
be easily searched.

Cons of ISAM

 This method requires extra space in the disk to store the index value. When the new records
are inserted, then these files have to be reconstructed to maintain the sequence.
 When the record is deleted, then the space used by it needs to be released. Otherwise, the
performance of the database will slow down. 

54
Expected Output: If record of employee does not exist an appropriate message is displayed
otherwise theemployee’s details are displayed.

Conclusion: This program gives us the knowledge index sequential file organization.

55
Assignment-13

Title:

Design a mini project to implement Snake and Ladders Game using Python.

Learning Objectives:

 To understand concept & features of Python Programming.

Learning Outcome:

 Analyze working of various python file scripts (snakes_ladders.py), resources files and sound
files.

Theory:

Python:

 Python is a high-level, general-purpose and a very popular programming language.


 Python programming language (latest Python 3) is being used in web development,
Machine Learning applications, along with all cutting-edge technology in Software
Industry.
 Python Programming Language is very well suited for Beginners, also for experienced
programmers with other programming languages like C++ and Java.

 Python Programming Language:


1. Python is currently the most widely used multi-purpose, high-level programming
language.
2. Python allows programming in Object-Oriented and Procedural paradigms.
3. Python programs generally are smaller than other programming languages like Java.
Programmers have to type relatively less and indentation requirement of the language,
makes them readable all the time.
4. Python language is being used by almost all tech-giant companies like – Google, Amazon,
Facebook, Instagram, Dropbox, Uber… etc.
5. The biggest strength of Python is huge collection of standard library which can be used for
the following:
 Machine Learning
 GUI Applications (like Kivy, Tkinter, PyQt etc. )
 Web frameworks like Django (used by YouTube, Instagram, Dropbox)
 Image processing (like OpenCV, Pillow)
 Web scraping (like Scrapy, BeautifulSoup, Selenium)

56
 Test frameworks
 Multimedia
 Scientific computing

This Snakes and Ladders Game contains python file scripts (snakes_ladders.py), resources files and
sound files. The gameplay of the system, which is the user can choose an option either to play multiple
participant or with the computer.

Beginning of the game, the player needs to roll the dice and in the wake of moving it the game moves
the token consequently as indicated by the dice number. The interactivity is like the genuine one. Here,
the player likewise gets one more opportunity to roll the dice at whatever point he/she gets 6 number.

There are quantities of stepping stools and snakes in the game which causes the player to update or
minimization the square number. The player who arrives at the last square of the track is the champ.

Snakes and Ladders Game

 Step 1: Create a project name.


First when you finished installed the Pycharm IDE in your computer, open it and then

create a “project name” after creating a project name click the “create” button.

 Step 2: Create a python file.


Second after creating a project name, “right click” your project name and then click “new”

after that click the “python file“.

 Step 3: Name your python file.

57
Third after creating a python file, Name your python file after that click “enter“.

 Step 4: The Python code.


The actual coding of how to create Snakes and Ladders Game in Python

Expected Output: Implementation of Snake and Ladders Game using Python.

Conclusion: Successfully implemented of a mini project using python.

58

You might also like