0% found this document useful (0 votes)
34 views208 pages

Wa0004.

Here is the program to implement Fibonacci series using recursion: def fibonacci(n): if n <= 1: return n else: return(fibonacci(n-1) + fibonacci(n-2)) terms = int(input("How many terms? ")) if terms <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(terms): print(fibonacci(i)) This program takes the number of terms as input from the user. It defines a recursive function fibonacci() that calculates the nth Fibonacci number. The base cases are n<=1, which returns n.

Uploaded by

rrajalakshmi
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)
34 views208 pages

Wa0004.

Here is the program to implement Fibonacci series using recursion: def fibonacci(n): if n <= 1: return n else: return(fibonacci(n-1) + fibonacci(n-2)) terms = int(input("How many terms? ")) if terms <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(terms): print(fibonacci(i)) This program takes the number of terms as input from the user. It defines a recursive function fibonacci() that calculates the nth Fibonacci number. The base cases are n<=1, which returns n.

Uploaded by

rrajalakshmi
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/ 208

C.

ABDUL HAKEEM COLLEGE OF ENGINEERING


AND TECHNOLOGY, MELVISHARAM

Hakeem Nagar, Melvisharam - 632 509, Vellore District, Tamil Nadu, India. (Approved
by AICTE, New Delhi and Affiliated to Anna University, Chennai)

(Accredited by NBA & with ‘A’ grade by NAAC and ISO 9001:2008 Certified Institution)
(Regd. Under Sec 2(F) & 12(B) of the UGC Act 1956)

Department of Information Technology

CD3281-DATA STRUCTURES AND ALGORITHMS LABORATORY


RECORD

(Regulation - 2021)

Name of the Student :

Register Number :

Degree / Branch :

Year / Semester :

Academic Year :

1
C. ABDUL HAKEEM COLLEGE OF ENGINEERING &
TECHNOLOGY

Hakeem Nagar, Melvisharam - 632 509, Vellore District, Tamil Nadu, India. (Approved by
AICTE, New Delhi and Affiliated to Anna University, Chennai)

(Accredited by NBA & with ‘A’ grade by NAAC and ISO 9001:2008 Certified Institution)
(Regd. Under Sec 2(F) & 12(B) of the UGC Act 1956)

Name:

Year: Semester: Degree/Branch: B.Tech. / IT

Subject Name: Data Structure and Algorithms laboratory Subject Code: CD3281

University Register Number:

CERTIFICATE

Certified that this is the bonafide record of work done by the above student in CD3281-DATA

STRUCTURES AND ALGORITHMS LABORATORY during the year 2021 - 2022.

Signature of Head of the Department Signature of Lab In-charge

Submitted for the University Practical Examination held on

Date: Centre code: 5106

Internal Examiner: External Examiner:

2
INDEX
EX.NO DATE PROGRAM PG.NO SIGN
1 IMPLEMENT SIMPLE ADTS AS 5
PYTHON CLASSES
2 IMPLEMENT RECURSIVE 11
ALGORITHMS IN PYTHON
2(A) TOWER OF HANOI 11
2(B) FIBBONACCI SERIES 13
2(C) FACTORIAL OF A NUMBER 17
3 LIST ADT USING PYTHON 20
ARRAYS
4 LINKED LIST IMPLEMENTATION 28
4(A) SINGLY LINKED LIST 28
4(B) DOUBLY LINKED LIST 35
4(C) CIRCULAR SINGLY LINKED LIST 46
4(D) CIRCULAR DOUBLY LINKED LIST 54
5 STACK AND QUEUE 62
IMPLEMENTATION
5(A) STACK IMPLEMENTATION 62
5(B) QUEUE IMPLEMENTATION 67
6 APPLICATIONS 72
6(A) APPLICATIONS OF LIST 72
6(B) APPLICATION OF STACK 80
6(C) APPLICATION OF QUEUE 84
7 SORTING AND SEARCHING 89
ALGORITHM
7)(A) SORTING ALGORITHM-BUBBLE 89
SORT
7)(B) SORTING ALGORITHM- 92
SELECTION SORT
7)(C) SORTING ALGORITHM-INSERTION 95
SORT
7)(D) SORTING ALGORITHM-QUICK 98
SORT
7)(E) SORTING ALGORITHM-MERGE 106
SORT
7)(F) SEARCHING ALGORITHM-LINEAR 111
SEARCH
7)(G) SEARCHING ALGORITHM-BINARY 114
SEARCH

3
8 IMPLEMENTATION OF HASH 117
TABLES
8(A) HASHING WITH LINEAR PROBING 117
8(B) HASHING WITH QUADRATIC 125
PROBING
8(C) HASHING WITH DOUBLE 133
HASHING
9 TREE REPRESENTATION AND 141
TRAVERSAL ALGORITHM
9(A) ARRAY REPRESENTATION 141
9(B) LINKEDLIST REPRESENTATION 145
9(C) TRAVERSAL ALGORITHM 151
10 IMPLEMENTATION OF BINARY 156
SEARCH TREE
10(A) BINARY SEARCH TREE 156
10(B) AVL TREE 161
11 IMPLEMENTATION OF HEAPS 171
11(A) MAX HEAP 171
11(B) MIN HEAP 175
12 GRAPH REPRESENTATION AND 178
TRAVERSAL ALGORITHM
12(A) GRAPH REPRESENTATION— 178
ADJACENCY LIST
12(B) GRAPH REPRESENTATION— 183
ADJACENCY MATRIX
12(C) TRAVERSAL ALGORITHM—BFS 189
12(D) TRAVERSAL ALGORITHM—DFS 193
13 SINGLE SOURCE SHORTEST PATH 196
ALGORITHM
14 MINIMUM SPANNING TREE 199
ALGORITHM
14(A) KRUSKAL’S ALGORITHM 199
14(B) PRIM’S ALGORITHM 204

4
EX.NO:1
IMPLEMENT SIMPLE ADTS AS PYTHON CLASSES
DATE:

AIM:
To write a python program to implement ADTS as python classes.
ALGORITHM:

 Start.
 Create a node with value null.
 Then push an element new.
 Check if new is not null otherwise insertion cannot be done.
 Then put item into data part of new and assign top its link.
 Top is updated to the new value.And element is inserted.
 For popping,check if the item is not null,otherwise stack is
empty underflow condition.
 The pointer is then made to point the next element and set head
link is assigned to the pointer’s value.
 Remove the element from the link list.
 Peek value is storted or printed by returning node at which top is
pointing.
 Stop.

5
PROGRAM:
class Stack:
def __init__ (self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
#Queue ADT
class Queue:
def __init__ (self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self,item):
self.items.append(item)

6
def dequeue(self):
return self.items.pop(0)
def front(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
s=Stack()
print('Stack operation examples')
print(s.isEmpty())
s.push(5)
s.push('python')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(11.5)
print(s.pop())
print(s.size())
# Queue ADT operation example
q=Queue()
print('Queue operation examples')
print(q.isEmpty())

7
q.enqueue(5)
q.enqueue('python')
print(q.front())
q.enqueue(True)
print(q.size())
print(q.isEmpty())
q.enqueue(11.5)
print(q.dequeue())
print(q.dequeue())
print(q.size())

8
OUTPUT:
Stack operation examples
True
python
3
False
11.5
3
Queue operation examples
True
python
3
False
5
python
2

9
RESULT:

Thus the given program has been executed and verified successfully.

10
EX.NO:2(A)
IMPLEMENT RECURSIVE ALGORITHMS IN
DATE: PYTHON
TOWER OF HANOI

AIM:
To write a program to implement tower of Hanoi using recursive
algorithm.
ALGORITHM:

 Start.
 Create a tower_of_hanoi recursive function and pass two
arguments: the number of disks n and the name of the rods such
as source, auxiliary, and target.
 define the base case when the number of disks is 1. In this case,
simply move the one disk from the source to target and return.
 Now, move remaining n-1 disks from source to auxiliary using
the target as the auxiliary.
 Then, the remaining 1 disk move on the source to target.
 Move the n-1 disks on the auxiliary to the target using the
source as the auxiliary.
 Stop.

11
PROGRAM:
def tower_of_hanoi(disks, source, auxiliary, target):
if(disks == 1):
print('Move disk 1 from rod {} to rod {}.'.format(source, target))
return
tower_of_hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from rod {} to rod {}.'.format(disks, source,
target))
tower_of_hanoi(disks - 1, auxiliary,source, target)
disks = int(input('Enter the number of disks: '))
tower_of_hanoi(disks, 'A', 'B', 'C')

12
OUTPUT:
Enter the number of disks: 3
Move disk 1 from rod A to rod C.
Move disk 2 from rod A to rod B.
Move disk 1 from rod C to rod B.
Move disk 3 from rod A to rod C.
Move disk 1 from rod B to rod A.
Move disk 2 from rod B to rod C.
Move disk 1 from rod A to rod C.

RESULT:
Thus the given program has been executed and verified successfully

13
EX.NO:2(B)
IMPLEMENTATION OF RECURSIVE
DATE: ALGORITHM
FIBONACCI SERIES

AIM:
To write a program to implement fibonacci series using recursive
algorithm.
ALGORITHM:

 Start.
 Create a fibbonaci recursive function and give the number as
argument
 Declare a variable with value(number)
 Check whether the number is less than and equal to zero, then
print enter a positive number
 Else, set a loop for the given number and call the recursive
function
 Check whether the number is less than and equal to 1, return
number
 Else, return (recur_fib(n-1)+recur_fib(n-2))
 Stop.

14
PROGRAM:
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 5
if nterms <= 0:
print(" enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

15
OUTPUT:
Fibonacci sequence:
0
1
1
2
3

RESULT:
Thus the given program has been executed and verified successfully.

16
EX.NO:2(C) IMPLEMENT RECURSIVE ALGORITHMS IN
DATE: PYTHON
FACTORIAL OF A NUMBER

AIM:
To write a program to implement factorial of a number using
recursive algorithm.
ALGORITHM:

 Start.
 Create a factorial recursive function and give the number as
argument
 Declare a variable with value(number)
 If the number is 1, return number
 Else , return (number* recur_factorial(n-1)).
 Stop.

17
PROGRAM:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num =int(input('enter number:'))
if num < 0:
print(" factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

18
OUTPUT:
enter number:4
The factorial of 4 is 24

RESULT:
Thus the given program has been executed and verified successfully.

19
EX.NO:3
DATE: LIST ADT USING PYTHON ARRAYS

AIM:
To write a program to implement list ADT using array.
ALGORITHM:

 Start.
 Initialize class variables
 Define the insert function and pass the class variables as
arguments
 Display the list of values
 Define the search function and it iterate all values present in the
list
 Check whether the element is present, if it is found then print
element is found
 Else, print element is not found
 Define the delete function and find the element which is to be
deleted
 Delete the element from the list
 Define the update function and set the index position then
update the element
 Display the elements in list.
 Stop.

20
PROGRAM:
class Student():
def __init__ (self, name, rollno, m1, m2):
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
def accept(self, Name, Rollno, marks1, marks2 ):
ob = Student(Name, Rollno, marks1, marks2 )
print(ob)
ls.append(ob)
def display(self, ob):
print("Name : ", ob.name)
print("RollNo : ", ob.rollno)
print("Marks1 : ", ob.m1)
print("Marks2 : ", ob.m2)
print("\n")
def search(self, rn):
for i in range(len(ls)):
if(ls[i].rollno == rn):
return i
def delete(self, rn):

21
i = obj.search(rn)
del ls[i]
def update(self, rn, No):
i = obj.search(rn)
roll = No
ls[i].rollno = roll;
ls =[]
obj = Student('', 0, 0, 0)
print("\nOperations used, ")
print("\n1.Accept Student details\n2.Display Student Details\n"
"3.Search Details of a Student\n4.Delete Details of Student"
"\n5.Update Student Details\n6.Exit")
obj.accept("A", 1, 100, 100)
obj.accept("B", 2, 90, 90)
obj.accept("C", 3, 80, 80)
print("\n")
print("\nList of Students\n")
for i in range(len(ls)):
obj.display(ls[i])
print("\n Student Found, ")
s = obj.search(2)
obj.display(ls[s])
obj.delete(2)

22
print(len(ls))
print("List after deletion")
for i in range(len(ls)):
obj.display(ls[i])

obj.update(3, 2)
print(len(ls))
print("List after updation")
for i in range(len(ls)):
obj.display(ls[i])

23
OUTPUT:

Operations used,

1.Accept Student details


2.Display Student Details
3.Search Details of a Student
4.Delete Details of Student
5.Update Student Details
6.Exit
<__main__.Student object at 0x000001E416C116A0>
<__main__.Student object at 0x000001E416C315E0>
<__main__.Student object at 0x000001E416D60E20>

List of Students

Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100

24
Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90

Name : C
RollNo : 3
Marks1 : 80
Marks2 : 80

Student Found,
Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90

25
2
List after deletion
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100

Name : C
RollNo : 3
Marks1 : 80
Marks2 : 80

2
List after updation
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100

26
Name : C
RollNo : 2
Marks1 : 80
Marks2 : 80

RESULT:
Thus the given program has been executed and verified successfully.

27
EX.NO:4(A)
LINKED LIST IMPLEMENTATION
DATE: SINGLY LINKED LIST

AIM:
To write a python program for to implementation of singly linked
list.
ALGORITHM:

 Start
 Defining the Node class which actually holds the data as well as
the next element link
 Defining the Linked List class
 Initializing the Linked List constructor with head variable
 Defining the insert() method which is used to add elements to
the Singly Linked List
o Checking whether or not the Linked List is empty
o Adding a Node to the beginning of the Linked List
o Adding a Node to the end of the Linked List
o Adding a Node in the middle of the Linked List
 Defining the delete() method which is used to delete elements
from the Singly Linked List
o Checking whether or not the Linked List is empty or not,
or deleting the last element in the Linked List
o Deleting the first element of the Linked List
o Deleting the last element of the Linked List
o Deleting an element by position or by value
 Defining the display() method which is used to present the
Singly Linked List in a user- comprehendible form.
 Stop.

28
PROGRAM:
class SLinkedList:
def __init__(self):
self.headval = None
def AtBegining(self,newdata):
NewNode = Node(newdata)
NewNode.nextval = self.headval
self.headval = NewNode
def AtEnd(self, newdata):
NewNode = Node(newdata)
if self.headval is None:
self.headval = NewNode
return
laste = self.headval
while(laste.nextval):
laste = laste.nextval
laste.nextval=NewNode
def Inbetween(self,middle_node,newdata):
if middle_node is None:
print("The mentioned node is absent")
return
NewNode = Node(newdata)

29
NewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode
def search_item(self, x):
if self.headval is None:
print("List has no elements")
return
n = self.headval
while n is not None:
if n.dataval == x:
print("Item found")
return True
n =n.nextval
print("item not found")
return False
def getCount(self):
temp = self.headval # Initialise temp
count = 0 # Initialise count
while (temp):
count += 1
temp = temp.nextval
return count
def RemoveNode(self, Removekey):

30
HeadVal = self.headval
if (HeadVal is not None):
if (HeadVal.dataval == Removekey):
self.headval = HeadVal.nextval
HeadVal = None
return
while (HeadVal is not None):
if HeadVal.dataval == Removekey:
break
prev = HeadVal
HeadVal = HeadVal.nextval
if (HeadVal == None):
return
prev.nextval = HeadVal.nextval
HeadVal = None
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
list = SLinkedList()
list.headval = Node("1")

31
e2 = Node("2")
e3 = Node("3")
list.headval.nextval = e2
e2.nextval = e3
list.AtBegining("4")
list.AtEnd("5")
list.Inbetween(list.headval.nextval,"6")
list.search_item("3")
print ("Count of nodes is(before removal) :",list.getCount())
list.listprint()
list.RemoveNode("2")
print ("Count of nodes is(after removal) :",list.getCount())
list.listprint()

32
OUTPUT:
Item found
Count of nodes is(before removal) : 6
4
1
6
2
3
5
Count of nodes is(after removal) : 5
4
6
2
3
5

33
RESULT:
Thus the given program has been executed and verified successfully.

34
EX.NO:4(B)
LINKED LIST IMPLEMENTATION
DATE: DOUBLY LINKED LIST

AIM:
To write a python program for to implementation of doubly linked
list.
ALGORITHM:

 Start.
 Defining the Node class which actually holds the data, previous
and next element link
 Defining the Linked List class
 Initializing the Linked List constructor with head variable
 Defining the insert() method which is used to add elements to
the doubly Linked List
o Checking whether or not the Linked List is empty
o Adding a Node to the beginning of the Linked List
o Adding a Node to the end of the Linked List
o Adding a Node in the middle of the Linked List
 Defining the delete() method which is used to delete elements
from the doubly Linked List
o Checking whether or not the Linked List is empty or not,
or deleting the last element in the Linked List
o Deleting the first element of the Linked List
o Deleting the last element of the Linked List
o Deleting an element by position or by value
 Defining the display() method which is used to present the
doubly Linked List in a user- comprehendible form.
 Stop.

35
PROGRAM:
class Node:
def __init__ (self, data):
self.item = data
self.nref = None
self.pref = None
class DoublyLinkedList:
def __init__ (self):
self.start_node = None
self.tail = None
self.count = 0
def insert_in_emptylist(self, data):
if self.start_node is None:
new_node = Node(data)
self.start_node = new_node
else:
print("list is not empty")
def insert_at_start(self, data):
if self.start_node is None:
new_node = Node(data)
self.start_node = new_node
print("node inserted")

36
return
new_node = Node(data)
new_node.nref = self.start_node
self.start_node.pref = new_node
self.start_node = new_node
def insert_at_end(self, data):
if self.start_node is None:
new_node = Node(data)
self.start_node = new_node
return
n = self.start_node
while n.nref is not None:
n = n.nref
new_node = Node(data)
n.nref = new_node
new_node.pref = n
def insert_after_item(self, x, data):
if self.start_node is None:
print("List is empty")
return
else:
n = self.start_node

37
while n is not None:
if n.item == x:
break
n = n.nref
if n is None:
print("item not in the list")
else:
new_node = Node(data)
new_node.nref = n.nref
n.nref = new_node
new_node.pref = n
if new_node.nref is not None:
new_node.nref.pref = new_node
n.nref = new_node
def insert_before_item(self, x, data):
if self.start_node is None:
print("List is empty")
return
else:
n = self.start_node
while n is not None:
if n.item == x:

38
break
n = n.nref
if n is None:
print("item not in the list")
else:
new_node = Node(data)
new_node.nref = n
new_node.pref = n.pref
if n.pref is not None:
n.pref.nref = new_node
n.pref = new_node
def traverse_list(self):
if self.start_node is None:
print("List has no element")
return
else:
n = self.start_node
while n is not None:
print(n.item , " ")
n = n.nref
def delete_at_start(self):
if self.start_node is None:

39
print("The list has no element to delete")
return
if self.start_node.nref is None:
self.start_node = None
return
self.start_node = self.start_node.nref
self.start_prev = None;
def delete_at_end(self):
if self.start_node is None:
print("The list has no element to delete")
return
if self.start_node.nref is None:
self.start_node = None
return
n = self.start_node
while n.nref is not None:
n = n.nref
n.pref.nref = None
def delete_element_by_value(self, x):
if self.start_node is None:
print("The list has no element to delete")
return

40
if self.start_node.nref is None:
if self.start_node.item == x:
self.start_node = None
else:
print("Item not found")
return
if self.start_node.item == x:
self.start_node = self.start_node.nref
self.start_node.pref = None
return
n = self.start_node
while n.nref is not None:
if n.item == x:
break;
n = n.nref
if n.nref is not None:
n.pref.nref = n.nref
n.nref.pref = n.pref
else:
if n.item == x:
n.pref.nref = None
else:

41
print("Element not found")
new_linked_list = DoublyLinkedList()
new_linked_list.insert_in_emptylist(50)
new_linked_list.insert_at_start(10)
new_linked_list.insert_at_start(5)
print(new_linked_list.traverse_list())
new_linked_list.insert_at_end(29)
new_linked_list.insert_at_end(39)
print(new_linked_list.traverse_list())
new_linked_list.insert_after_item(50, 65)
print(new_linked_list.traverse_list())
new_linked_list.insert_before_item(29, 100)
print(new_linked_list.traverse_list())
new_linked_list.delete_at_start()
print(new_linked_list.traverse_list())
new_linked_list.delete_at_end()
print(new_linked_list.traverse_list())
new_linked_list.delete_element_by_value(65)
print(new_linked_list.traverse_list())

42
OUTPUT:
5
10
50
None
5
10
50
29
39
None
5
10
50
65
29
39
None
5
10
50
65

43
100
29
39
None
10
50
65
100
29
39
None
10
50
65
100
29
None
10
50
100
29
None

44
RESULT:
Thus the given program has been executed and verified successfully.

45
EX.NO:4(c)
LINKED LIST IMPLEMENTATION
DATE: CIRCULAR SINGLY LINKED LIST

AIM:
To write a python program for the implementation of circular singly
linked list.
ALGORITHM:

 Start.
 Defining the Node class which actually holds the data as well as
next element link
 Defining the Linked List class
 Initializing the Linked List constructor with head variable
 Defining the insert() method which is used to add elements to
the circular singly Linked List
o Checking whether or not the Linked List is empty
o Adding a Node to the beginning of the Linked List
o Adding a Node to the end of the Linked List
o Adding a Node in the middle of the Linked List
 Defining the delete() method which is used to delete elements
from the circular singly Linked List
o Checking whether or not the Linked List is empty or not,
or deleting the last element in the Linked List
o Deleting the first element of the Linked List
o Deleting the last element of the Linked List
o Deleting an element by position or by value
 Defining the display() method which is used to present the
circular singly Linked List in a user- comprehendible form.
 Stop.

46
PROGRAM:
class Node:
def __init__ (self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__ (self):
self.head = None
def get_node(self, index):
if self.head is None:
return None
current = self.head
for i in range(index):
current = current.next
if current == self.head:
return None
return current
def get_prev_node(self, ref_node):
if self.head is None:
return None
current = self.head
while current.next != ref_node:

47
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.next = ref_node.next
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)
def insert_at_end(self, new_node):
if self.head is None:
self.head = new_node
new_node.next = new_node
else:
self.insert_before(self.head, new_node)
def insert_at_beg(self, new_node):
self.insert_at_end(new_node)
self.head = new_node
def remove(self, node):
if self.head.next == self.head:
self.head = None
else:
prev_node = self.get_prev_node(node)

48
prev_node.next = node.next
if self.head == node:
self.head = node.next
def display(self):
if self.head is None:
return
current = self.head
while True:
print(current.data, end = ' ')
current = current.next
if current == self.head:
break
a_cllist = CircularLinkedList()
print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')
while True:
print('The list: ', end = '')

49
a_cllist.display()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_cllist.insert_at_beg(new_node)
elif position == 'end':
a_cllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_cllist.insert_after(ref_node, new_node)

50
elif suboperation == 'before':
a_cllist.insert_before(ref_node, new_node)
if operation == 'remove':
index = int(do[1])
node = a_cllist.get_node(index)
if node is None:
print('No such index.')
continue

a_cllist.remove(node)
elif operation == 'quit':
break

51
OUTPUT:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 2 at beg
The list: 2
What would you like to do? insert 4 at beg
The list: 4 2
What would you like to do? insert 5 at beg
The list: 5 4 2
What would you like to do? insert 7 at end
The list: 5 4 2 7
What would you like to do? insert 3 after 2
The list: 5 4 2 3 7
What would you like to do? insert 9 before 3
The list: 5 4 2 9 3 7
What would you like to do? remove 3

52
The list: 5 4 2 3 7
What would you like to do? quit

RESULT:
Thus the given program has been executed and verified successfully.

53
EX.NO:4(D)
LINKED LIST IMPLEMENTATION
DATE: CIRCULAR DOUBLY LINKED LIST

AIM:
To write a python program for to implementation of circular doubly
linked list.
ALGORITHM:

 Start.
 Defining the Node class which actually holds the data as well as
next element link
 Defining the Linked List class
 Initializing the Linked List constructor with head variable
 Defining the insert() method which is used to add elements to
the circular doubly Linked List
o Checking whether or not the Linked List is empty
o Adding a Node to the beginning of the Linked List
o Adding a Node to the end of the Linked List
o Adding a Node in the middle of the Linked List
 Defining the delete() method which is used to delete elements
from the circular doubly Linked List
o Checking whether or not the Linked List is empty or not,
or deleting the last element in the Linked List
o Deleting the first element of the Linked List
o Deleting the last element of the Linked List
o Deleting an element by position or by value
 Defining the display() method which is used to present the
circular doubly Linked List in a user- comprehendible form.
 Stop.

54
PROGRAM:
class Node:
def __init__ (self, data):
self.data = data
self.next = None
self.prev = None
class CircularDoublyLinkedList:
def __init__ (self):
self.first = None
def get_node(self, index):
current = self.first
for i in range(index):
current = current.next
if current == self.first:
return None
return current
def insert_after(self, ref_node, new_node):
new_node.prev = ref_node
new_node.next = ref_node.next
new_node.next.prev = new_node
ref_node.next = new_node
def insert_before(self, ref_node, new_node):

55
self.insert_after(ref_node.prev, new_node)
def insert_at_end(self, new_node):
if self.first is None:
self.first = new_node
new_node.next = new_node
new_node.prev = new_node
else:
self.insert_after(self.first.prev, new_node)
def insert_at_beg(self, new_node):
self.insert_at_end(new_node)
self.first = new_node
def remove(self, node):
if self.first.next == self.first:
self.first = None
else:
node.prev.next = node.next
node.next.prev = node.prev
if self.first == node:
self.first = node.next
def display(self):
if self.first is None:
return

56
current = self.first
while True:
print(current.data, end = ' ')
current = current.next
if current == self.first:
break
a_cdllist = CircularDoublyLinkedList()
print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')
while True:
print('The list: ', end = '')
a_cdllist.display()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])

57
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_cdllist.insert_at_beg(new_node)
elif position == 'end':
a_cdllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cdllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_cdllist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_cdllist.insert_before(ref_node, new_node)
if operation == 'remove':
index = int(do[1])
node = a_cdllist.get_node(index)
if node is None:

58
print('No such index.')
continue
a_cdllist.remove(node)
elif operation == 'quit':
break

59
OUTPUT:

Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 2 at beg
The list: 2
What would you like to do? insert 4 at beg
The list: 4 2
What would you like to do? insert 5 at beg
The list: 5 4 2
What would you like to do? insert 7 at end
The list: 5 4 2 7
What would you like to do? insert 3 after 2
The list: 5 4 2 3 7
What would you like to do? insert 9 before 3
The list: 5 4 2 9 3 7

60
What would you like to do? remove 3
The list: 5 4 2 3 7
What would you like to do? quit

RESULT:
Thus the given program has been executed and verified successfully.

61
EX.NO:5(A)
STACK AND QUEUE IMPLEMENTATION
DATE: STACK IMPLEMENTATION

AIM:
To write a program to implement stack using linked list.
ALGORITHM:

 Start.
 Create a node with value Null.
 Then push an element new
 Check if new is not null otherwise insertion cannot be done.
 Then put Item into data part of new and assign top to its link
 Top is updated to the new value. And element is inserted.
 For popping, check if the item is not null, otherwise stack is
empty i.e underflow condition.
 The pointer is then made to point the next element andset_head
link is assigned to the pointer's value.
 Remove the element from the link list.
 Peek value is stored or printed by returning node at which top is
pointing
 Stop.

62
PROGRAM:
class Node:
def __init__ (self, data=None, next=None):
self.data = data
self.next = next
class Stack:
def __init__ (self):
self.top = None
def push(self, data):
if self.top is None:
self.top = Node(data, None)
return
self.top = Node(data, self.top)

def pop(self):
if self.top is None:
return
temp = self.top

if self.top is not None:


self.top = self.top.next
temp.next = None

63
return temp.data
def peek(self):
return self.top.data
def clearstack(self):
self.top = None
def emptystack(self):
if self.top is None:
return True
return False
def display(self):
itr = self.top
sstr = ' '
while itr:
sstr += str(itr.data) + '-->'
itr = itr.next
print(sstr)

if __name__ == "__main__":
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(40)

64
stack.peek()
stack.display()
stack.pop()
stack.push(30)
stack.display()

65
OUTPUT:
40-->20-->10-->
30-->20-->10-->

RESULT:
Thus the given program has been executed and verified successfully.

66
EX.NO:5(B)
STACK AND QUEUE IMPLEMENTATION
DATE: QUEUE IMPLEMENTATION

AIM:
To write a program to implement queue using linked list.
ALGORITHM:

 Start.
 Create a newNode with the given value and set the node's
pointer to NULL.
 Check whether queue is EMPTY.
 If it is EMPTY, set FRONT and REAR to newNode.
 Else, set the pointer of REAR to newNode and make REAR as
the newNode.
 Check if the queue is EMPTY.
 If it is EMPTY, then display "EMPTY QUEUE" and exit.
 Else, create a temporary node and set it to FRONT.
 Make the next node as FRONT and delete the temporary node.
 Display the nodes in queue.
 Stop.

67
PROGRAM:
class Node:
def __init__ (self, data=None, next=None, prev=None):
self.data = data #creating a storage for assigning value
self.next = next #pointer to the next value
self.prev = prev #pointer to the already existing previous value.
class Queue:
def __init__ (self):
self.front = self.rear = None
def enqueue(self, data):
if self.rear is None:
self.front = self.rear = Node(data, None)
return
self.rear.next = Node(data, None)
self.rear.next.prev = self.rear
self.rear = self.rear.next
def dequeue(self):
if self.front is None:
raise Exception('empty queue')
temp = self.front.data
self.front = self.front.next
if self.front is None:

68
self.rear = None
return
self.front.prev = None
return temp
def clearqueue(self):
self.front = self.rear = None
def emptyqueue(self):
if self.front is None:
return True
return False
def display(self):
itr = self.front
sstr = ' '
while itr:
sstr += str(itr.data) + '-->'
itr = itr.next
print(sstr)
if __name__ == "__main__":
queue = Queue()
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)

69
queue.display()
queue.dequeue()
#queue.dequeue()
#queue.dequeue()
queue.display()
queue.enqueue(40)
queue.enqueue(50)
queue.enqueue(60)
queue.display()
queue.clearqueue()
queue.display()

70
OUTPUT:

10-->20-->30-->
20-->30-->
20-->30-->40-->50-->60-->

RESULT:
Thus the given program has been executed and verified successfully.

71
EX.NO:6(A) APPLICATIONS
DATE: APPLICATIONS OF LIST

AIM:
To write a program to implement matrix multiplication using list.
ALGORITHM:

 Start.
 Initialize N*N matrix
 Enter the row and column of the first (a) matrix.
 Enter the row and column of the second (b) matrix.
 Enter the elements of the first (a) and second (b) matrix.
 Print the elements of the first (a) and second(b) matrix in matrix
form.
 Set a loop up to row.
 Set an inner loop up to the column.
 Set another inner loop up to the column.
 Add the first (a) and second (b) matrix and store the element in
the third matrix (c)
 subtract the first (a) and second (b) matrix and store the element
in the third matrix (c)
 Multiply the first (a) and second (b) matrix and store the
element in the third matrix (c)
 divide the first (a) and second (b) matrix and store the element
in the third matrix (c)
 Print the final matrix.
 Stop.

72
PROGRAM:
A=[]
n=int(input("Enter N for N x N matrix : "))
print("Enter the element ::>")
for i in range(n):
row=[]
for j in range(n):
row.append(int(input()))
A. append(row)
print(A)
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print()
B=[]
n=int(input("Enter N for N x N matrix : "))
print("Enter the element ::>")
for i in range(n):
row=[]
for j in range(n):
row.append(int(input()))

73
B. append(row)
print(B)
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(B[i][j], end=" ")
print()
result = [[0,0,0], [0,0,0], [0,0,0]]
for i in range(n):
for j in range(len(A[0])):
result[i][j] = A[i][j] + B[i][j]
print("Resultant Matrix is ::>")
for r in result:
print("Resultant Matrix is ::>",r)
for i in range(n):
for j in range(len(A[0])):
result[i][j] = A[i][j] - B[i][j]
print("Resultant Matrix is ::>")
for r in result:
print("Resultant Matrix is ::>",r)
for i in range(n):
for j in range(len(A[0])):

74
result[i][j] = A[i][j] * B[i][j]
print("Resultant Matrix is ::>")
for r in result:
print("Resultant Matrix is ::>",r)
for i in range(n):
for j in range(n):
result[i][j] = result[j][i]
for r in result:
print("Resultant Matrix is ::>",r)
for i in range(n):
for j in range(len(A[0])):
result[i][j] = A[i][j] % B[i][j]
print("Resultant Matrix is ::>")
for r in result:
print("Resultant Matrix is ::>",r)

75
OUTPUT:
Enter N for N x N matrix : 3
Enter the element ::>
1
2
3
4
5
6
7
8
9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Display Array In Matrix Form
123
456
789
Enter N for N x N matrix : 3
Enter the element ::>
9
8
7

76
6
5
4
3
2
1
[[9, 8, 7], [6, 5, 4], [3, 2, 1]]
Display Array In Matrix Form
987
654
321
Resultant Matrix is ::>
Resultant Matrix is ::>
Resultant Matrix is ::>
Resultant Matrix is ::> [10, 10, 10]
Resultant Matrix is ::> [10, 10, 10]
Resultant Matrix is ::> [10, 10, 10]
Resultant Matrix is ::>
Resultant Matrix is ::>
Resultant Matrix is ::>
Resultant Matrix is ::> [-8, -6, -4]
Resultant Matrix is ::> [-2, 0, 2]

77
Resultant Matrix is ::> [4, 6, 8]
Resultant Matrix is ::>
Resultant Matrix is ::>
Resultant Matrix is ::>
Resultant Matrix is ::> [9, 16, 21]
Resultant Matrix is ::> [24, 25, 24]
Resultant Matrix is ::> [21, 16, 9]
Resultant Matrix is ::> [9, 24, 21]
Resultant Matrix is ::> [24, 25, 16]
Resultant Matrix is ::> [21, 16, 9]
Resultant Matrix is ::>
Resultant Matrix is ::>
Resultant Matrix is ::>
Resultant Matrix is ::> [1, 2, 3]
Resultant Matrix is ::> [4, 0, 2]
Resultant Matrix is ::> [1, 0, 0]

78
RESULT:
Thus the given program has been executed and verified successfully.

79
EX.NO:6(B)
APPLICATIONS
DATE: APPLICATIONS OF STACK

AIM:
To write a program to implement infix to postfix using stack.
ALGORITHM:

 Start.
 Scan the infix expression from left to right.
 If the scanned character is an operand, output it.
 Else,
o If the precedence of the scanned operator is greater than
the precedence of the operator in the stack(or the stack is
empty or the stack contains a ‘(‘ ), push it.
o Else, Pop all the operators from the stack which are greater
than or equal to in precedence than that of the scanned
operator. After doing that Push the scanned operator to the
stack.
 If the scanned character is an ‘(‘, push it to the stack.
 If the scanned character is an ‘)’, pop the stack and output it
until a ‘(‘ is encountered, and discard both the parenthesis.
 Repeat steps 2-6 until infix expression is scanned.
 Print the output
 Pop and output from the stack until it is not empty.
 Stop.

80
PROGRAM:
OPERATORS = set(['+', '-', '*', '/', '(', ')', '^'])
PRIORITY = {'+':1, '-':1, '*':2, '/':2, '^':3}
def infix_to_postfix(expression):
stack = [] # initially stack empty
output = '' # initially output empty
for ch in expression:
if ch not in OPERATORS:
output+= ch
elif ch=='(':
stack.append('(')
elif ch==')':
while stack and stack[-1]!= '(':
output+=stack.pop()
stack.pop()
else:
while stack and stack[-1]!='(' and
PRIORITY[ch]<=PRIORITY[stack[-1]]:
output+=stack.pop()
stack.append(ch)
while stack:
output+=stack.pop()
return output
81
expression = input('Enter infix expression')
print('infix expression: ',expression)
print('postfix expression: ',infix_to_postfix(expression))

82
OUTPUT:
Enter infix expression:a*b/c
infix expression: a*b/c
postfix expression: ab*c/

RESULT:
Thus the given program has been executed and verified successfully.

83
EX.NO:6(C) APPLICATIONS
DATE: APPLICATION OF QUEUE

AIM:
To write a program to implement queue using stack.
ALGORITHM:

 Start.
 Initialize with two stacks
 Add an item to the queue
 Move all elements from the first stack to the second stack
 push item into the first stack
 Move all elements back to the first stack from the second stack.
 Remove an item from the queue
 If the first stack is empty, return underflow
 Else, return the top item from the first stack
 Stop.

84
PROGRAM:
from collections import deque
class Queue:
def __init__ (self):
self.s1 = deque()
self.s2 = deque()
def enqueue(self, data):
while len(self.s1):
self.s2.append(self.s1.pop())
self.s1.append(data)
while len(self.s2):
self.s1.append(self.s2.pop())
def dequeue(self):
if not self.s1:
print("Underflow!!")
exit(0)
return self.s1.pop()
def printitem(self):
print("queue items:")
for e in self.s1:
print(e)
keys=[1,2,3,4,5]

85
q=Queue()
q.printitem()
print("the following queue item deleted:")
print(q.dequeue())
print("the following queue item deleted:")
print(q.dequeue())
q.printitem()

86
OUTPUT:
queue items:
5
4
3
2
1
the following queue item deleted:
1
the following queue item deleted:
2
queue items
5
4
3

87
RESULT:
Thus the given program has been executed and verified
successfully.

88
EX.NO:7(A) SORTING AND SEARCHING ALGORITHMS-
BUBBLE SORT
DATE:

AIM:
To write a program to implement sorting algorithm.
ALGORITHM:

 Start.
 Get the total number of items in the given list
 Determine the number of outer passes (n - 1) to be done. Its
length is list minus one
 Perform inner passes (n - 1) times for outer pass 1. Get the first
element value and compare it with the second value. If the
second value is less than the first value, then swap the positions
 Repeat step 3 passes until you reach the outer pass (n - 1). Get
the next element in the list then repeat the process that was
performed in step 3 until all the values have been placed in their
correct ascending order.
 Return the result when all passes have been done. Return the
results of the sorted list
 Stop.

89
PROGRAM:
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
print(arr)
arr = [5,3,8,6,7,2]
print ("Sorted array is:")
bubbleSort(arr)
for i in range(len(arr)):
print ("%d" %arr[i]),

90
OUTPUT:
Sorted array is:
[2, 3, 5, 6, 7, 8]
2
3
5
6
7
8

RESULT:
Thus the given program has been executed and verified successfully.

91
EX.NO:7(B)
SORTING AND SEARCHING ALGORITHMS-
DATE: SELECTION SORT

AIM:
To write a program to implement sorting algorithm.
ALGORITHM:

 Start.
 Get the value of n which is the total size of the array
 Partition the list into sorted and unsorted sections. The sorted
section is initially empty while the unsorted section contains the
entire list
 Pick the minimum value from the unpartitioned section and
placed it into the sorted section.
 Repeat the process (n – 1) times until all of the elements in the
list have been sorted.
 Spilt a list in two parts - sorted and unsorted.
 Iterate from arr[1] to arr[n] over the given array.
 Compare the current element to the next element.
 8.If the current element is smaller than the next element,
compare to the element before, Move to the greater elements
one position up to make space for the swapped element.
 Stop.

92
PROGRAM:
import sys
A = [5,3,8,6,7,2]
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
print ("Sorted array")
print(A)
for i in range(len(A)):
print("%d" %A[i]),

93
OUTPUT:
Sorted array
[2, 3, 5, 6, 7, 8]
2
3
5
6
7
8

RESULT:
Thus the given program has been executed and verified successfully.

94
EX.NO:7(C)
SORTING AND SEARCHING ALGORITHMS-
DATE: INSERTION SORT

AIM:
To write a program to implement sorting algorithm.
ALGORITHM:

 Start.
 Get the value of n which is the total size of the array
 Partition the list into sorted and unsorted sections. The sorted
section is initially empty while the unsorted section contains the
entire list
 Pick the minimum value from the unpartitioned section and
placed it into the sorted section.
 Repeat the process (n – 1) times until all of the elements in the
list have been sorted.
 Spilt a list in two parts - sorted and unsorted.
 Iterate from arr[1] to arr[n] over the given array.
 Compare the current element to the next element.
 8.If the current element is smaller than the next element,
compare to the element before, Move to the greater elements
one position up to make space for the swapped element
 Stop.

95
PROGRAM:
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
print(arr)
arr = [12, 11, 13, 5, 6]
print ("Sorted array is:")
insertionSort(arr)

96
OUTPUT:
Sorted array is:
[5, 6, 11, 12, 13]

RESULT:
Thus the given program has been executed and verified successfully.

97
EX.NO:7(D)
SORTING AND SEARCHING ALGORITHMS-
DATE: QUICK SORT

AIM:
To write a program to implement sorting algorithm.
ALGORITHM:

 Start.
 Select the Pivot Element as first, last, random and median
element
 Rearrange the Array
o A pointer is fixed at the pivot element. The pivot element
is compared with the elements beginning from the first
index.
o If the element is greater than the pivot element, a second
pointer is set for that element.
o Now, pivot is compared with other elements. If an element
smaller than the pivot element is reached, the smaller
element is swapped with the greater element found earlier.
o Again, the process is repeated to set the next greater
element as the second pointer. And, swap it with another
smaller element.
o The process goes on until the second last element is
reached.
o Finally, the pivot element is swapped with the second
pointer.
 Divide Subarrays
o Pivot elements are again chosen for the left and the right
sub-parts separately. And, step 2 is repeated.
o The subarrays are divided until each subarray is formed of
a single element. At this point, the array is sorted.
 Stop.

98
PROGRAM:

# python program to implement quick sort for ascending


order(first element)

def pivot_place(list1,first,last):
pivot = list1[first]
left = first+1
right = last
while True:
while left <= right and list1[left] <= pivot:
left = left+1
while left <= right and list1[right] >= pivot:
right = right-1
if right < left:
break
else:
list1[left], list1[right] = list1[right], list1[left]
list1[first], list1[right] = list1[right], list1[first]
return right
def quicksort(list1, first, last):
if first < last:
p=pivot_place(list1, first, last)

99
quicksort(list1, first, p-1)
quicksort(list1, p+1, last)

list1 = [56,26,93,17,31,44]

n=len(list1)
quicksort(list1, 0, n-1)
print(list1)

OUTPUT:
[17, 26, 31, 44, 56, 93]

# python program to implement quick sort for ascending


order(last element)

def pivot_place(list1,first,last):
pivot = list1[last]
left = first
right = last-1
while True:
while left <= right and list1[left] <= pivot:
left = left+1
while left <= right and list1[right] >= pivot:
100
right = right-1
if right < left:
break
else:
list1[left], list1[right] = list1[right], list1[left]
list1[last], list1[left] = list1[left], list1[last]
return left
def quicksort(list1, first, last):
if first < last:
p=pivot_place(list1, first, last)
quicksort(list1, first, p-1)
quicksort(list1, p+1, last)
list1 = [56,26,93,17,31,44]
n=len(list1)
quicksort(list1, 0, n-1)
print(list1)

OUTPUT:
[17, 26, 31, 44, 56, 93]

101
# python program to implement quick sort for ascending
order(random element)
import random
def pivot_place(list1,first,last):
rindex = random.randint(first, last)
list1[rindex], list1[last] = list1[last], list1[rindex]
pivot = list1[last]
left = first
right = last-1
while True:
while left <= right and list1[left] <= pivot:
left = left+1
while left <= right and list1[right] >= pivot:
right = right-1
if right < left:
break
else:
list1[left], list1[right] = list1[right], list1[left]
list1[last], list1[left] = list1[left], list1[last]
return left
def quicksort(list1, first, last):
if first < last:
p=pivot_place(list1, first, last)
102
quicksort(list1, first, p-1)
quicksort(list1, p+1, last)
list1 = [56,26,93,17,31,44]
n=len(list1)
quicksort(list1, 0, n-1)
print(list1)

OUTPUT:
[17, 26, 31, 44, 56, 93]

# python program to implement quick sort for ascending


order(median)

import statistics
def pivot_place(list1,first,last):
low = list1[first]
high = list1[last]
mid = (first+last)//2
pivot_val = statistics.median([low, list1[mid], high])
if pivot_val == low:
pindex = first
elif pivot_val == high:
pindex = last
103
else:
pindex = mid
list1[last], list1[pindex] = list1[pindex], list1[last]
pivot = list1[last]
left = first
right = last-1
while True:
while left <= right and list1[left] <= pivot:
left = left+1
while left <= right and list1[right] >= pivot:
right = right-1
if right < left:
break
else:
list1[left], list1[right] = list1[right], list1[left]
list1[last], list1[left] = list1[left], list1[last]
return left
def quicksort(list1, first, last):
if first < last:
p=pivot_place(list1, first, last)
quicksort(list1, first, p-1)
quicksort(list1, p+1, last)

104
list1 = [56,26,93,17,31,44]
n=len(list1)
quicksort(list1, 0, n-1)
print(list1)

OUTPUT:
[17, 26, 31, 44, 56, 93]

RESULT:
Thus the given program has been executed and verified successfully.
105
EX.NO:7(E)
SORTING AND SEARCHING ALGORITHMS-
DATE: MERGE SORT

AIM:
To write a program to implement sorting algorithm.
ALGORITHM:

 Start.
 Create a merge sort function and declare list of values in array
 Calculate the length for the given array
 If the length is less than and equal one the list is already sorted,
return the value.
 Else, divide the list recursively into two halves: L and R, until it
can no more be divided.
 Then, merge the smaller lists into new list in sorted order.
 Stop.

106
PROGRAM:
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):

107
arr[k] = R[j]
j += 1
k += 1
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
if __name__ == '__main__':
arr = [38, 27, 43, 3, 9, 82, 10]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)

108
OUTPUT:
Given array is
38
27
43
3
9
82
10
Sorted array is:
3
9
10
27
38
43
82

109
RESULT:
Thus the given program has been executed and verified successfully.

110
EX.NO:7(F)
SORTING AND SEARCHING ALGORITHMS-
DATE: LINEAR SEARCH

AIM:
To write a program to implement searching algorithm.
ALGORITHM:

 Start.
 Read the search element from the user
 Compare the search element with the first element in the list.
 If both are matched, then display "Given element is found!!!"
and terminate the function
 If both are not matched, then compare search element with the
next element in the list.
 Repeat steps 3 and 4 until search element is compared with last
element in the list.
 If last element in the list also doesn't match, then display
"Element is not found!!!" and terminate the function.
 Stop.

111
PROGRAM:
def linear_search(obj, item, start=0):
for i in range(start, len(obj)):
if obj[i] == item:
return i
return -1
arr=[1,2,3,4,5,6,7,8]
x=4
result=linear_search(arr,x)
if result==-1:
print ("element does not exist")
else:
print ("element exist in position %d" %result)

112
OUTPUT:
element exist in position 3

RESULT:
Thus the given program has been executed and verified successfully.

113
EX.NO:7(G)
SORTING AND SEARCHING ALGORITHMS-
DATE: BINARY SEARCH

AIM:
To write a program to implement searching algorithm.
ALGORITHM:

 Start.
 Given an input array that is supposed to be sorted in ascending
order.
 Take two variables which act as a pointer i.e, beg, and end.
 Beg assigned with 0 and the end assigned to the last index of the
array.
 Now, introduce another variable mid which is the middle of the
current array. Then computed as (low+high)/2.
 If the element present at the mid index is equal to the element to
be searched, then just return the mid index.
 If the element to be searched is smaller than the element present
at the mid index, move end to mid-1, and all RHS get discarded.
 If the element to be searched is greater than the element present
at the mid index, move beg to mid+1, and all LHS get discarded.
 Stop.

114
PROGRAM:
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
arr = [ 2, 3, 4, 10, 40 ]
x = 40
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")

115
OUTPUT:
Element is present at index 4

RESULT:
Thus the given program has been executed and verified successfully.

116
EX.NO:8(A)
IMPLEMENTATION OF HASH TABLES-
DATE: HASHING WITH LINEAR PROBING

AIM:
To write a program to implement hash table using linear probing.
ALGORITHM:

 Start.
 Initialize hash Table with all elements 0
 Create a method that checks if the hash table is full or not
 Create a method that returns position for a given element
 Create a method that inserts element inside the hash table
o checking if the table is full
o checking if the position is empty
o collision occurred , do linear probing
 Create a method that searches for an element in the table
 Returns position of element if found
 Else returns False
o If element is not found at position returned hash function
o Then first we search element from position+1 to end
o If not found then we search element from position-1 to 0
 Check if the element is stored between
position+1 to size.
 Now checking if the element is stored between
position-1 to 0
 Create a method to remove an element from the table
 Create a method to display the hash table
o Displaying the Table
 Stop.

117
PROGRAM:
class hashTable:
def __init__ (self):
self.size = int(input("Enter the Size of the hash table : "))
self.table = list(0 for i in range(self.size))
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
def hashFunction(self, element):
return element % self.size
def insert(self, element):
# checking if the table is full
if self.isFull():
print("Hash Table Full")
return False
isStored = False
position = self.hashFunction(element)
if self.table[position] == 0:

118
self.table[position] = element
print("Element " + str(element) + " at position " +
str(position))
isStored = True
self.elementCount += 1
else:
print("Collision has occured for element " + str(element) + " at
position " + str(position) + " finding new Position.")
while self.table[position] != 0:
position += 1
if position >= self.size:
position = 0
self.table[position] = element
isStored = True
self.elementCount += 1
return isStored
def search(self, element):
found = False
position = self.hashFunction(element)
self.comparisons += 1
if(self.table[position] == element):
return position
isFound = True

119
else:
temp = position - 1
while position < self.size:
if self.table[position] != element:
position += 1
self.comparisons += 1
else:
return position
position = temp
while position >= 0:
if self.table[position] != element:
position -= 1
self.comparisons += 1
else:
return position
if not found:
print("Element not found")
return False
def remove(self, element):
position = self.search(element)
if position is not False:
self.table[position] = 0

120
print("Element " + str(element) + " is Deleted")
self.elementCount -= 1
else:
print("Element is not present in the Hash Table")
return
def display(self):
print("\n")
for i in range(self.size):
print(str(i) + " = " + str(self.table[i]))
print("The number of element is the Table are : " +
str(self.elementCount))

table1 = hashTable()
table1.insert(89)
table1.insert(18)
table1.insert(49)
table1.insert(58)
table1.insert(9)
table1.display()
print()
print("The position of element 9 is : " + str(table1.search(9)))
print("The position of element 58 is : " + str(table1.search(58)))

121
print("\nTotal number of comaprisons done for searching = " +
str(table1.comparisons))
print()
table1.remove(18)
table1.display()

OUTPUT:
Enter the Size of the hash table : 2
Element 89 at position 1
Element 18 at position 0
Hash Table Full
Hash Table Full
Hash Table Full

0 = 18
1 = 89
The number of element is the Table are : 2

Element not found


The position of element 9 is : False
Element not found
The position of element 58 is : False
122
Total number of comaprisons done for searching = 6

Element 18 is Deleted

0=0
1 = 89
The number of element is the Table are : 1

123
RESULT:
Thus the given program has been executed and verified successfully.

124
EX.NO:8(B)
IMPLEMENTATION OF HASH TABLES-
DATE: HASHING WITH QUADRATIC PROBING

AIM:
To write a program to implement Hashing with Quadratic Probing.
ALGORITHM:

 Start.
 Initialize hash Table with all elements 0
 Create a method that checks if the hash table is full or not
 Create a method that returns position for a given element
 Replace with hash function
 Create a method to resolve collision by quadratic probing
method
o Start a loop to find the position and calculate new position
by quadratic probing
o If new position is empty then break out of loop and return
new Position
o Else, as the position is not empty increase i
 Create a method that inserts element inside the hash table
o Checking if the table is full
o Checking if the position is empty, if empty position found
, store the element
o Collision occurred, do quadratic probing
 Create a method that searches for an element in the table
 Returns position of element if found
 Else if element is not found at position returned hash function
and then search element using quadratic probing
o Start a loop to find the position and calculate new position
by quadratic probing
o If element at new position is equal to the required element
o Else, as the position is not empty increase i

125
 Create a method to remove an element from the table
 Create a method to display the hash table
 Stop.
PROGRAM:
class hashTable:
def __init__ (self):
self.size = int(input("Enter the Size of the hash table : "))
self.table = list(0 for i in range(self.size))
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
def hashFunction(self, element):
return element % self.size
def quadraticProbing(self, element, position):
posFound = False
limit = 50
i=1
while i <= limit:
newPosition = position + (i**2)

126
newPosition = newPosition % self.size
if self.table[newPosition] == 0:
posFound = True
break
else:
i += 1
return posFound, newPosition
def insert(self, element):
if self.isFull():
print("Hash Table Full")
return False
isStored = False
position = self.hashFunction(element)
if self.table[position] == 0:
self.table[position] = element
print("Element " + str(element) + " at position " +
str(position))
isStored = True
self.elementCount += 1
else:
print("Collision has occured for element " + str(element) + " at
position " + str(position) + " finding new Position.")
isStored, position = self.quadraticProbing(element, position)

127
if isStored:
self.table[position] = element
self.elementCount += 1
return isStored
def search(self, element):
found = False
position = self.hashFunction(element)
self.comparisons += 1
if(self.table[position] == element):
return position
else:
limit = 50
i=1
newPosition = position
while i <= limit:
newPosition = position + (i**2)
newPosition = newPosition % self.size
self.comparisons += 1
if self.table[newPosition] == element:
found = True
break
elif self.table[newPosition] == 0:

128
found = False
break
else:
i += 1
if found:
return newPosition
else:
print("Element not Found")
return found
def remove(self, element):
position = self.search(element)
if position is not False:
self.table[position] = 0
print("Element " + str(element) + " is Deleted")
self.elementCount -= 1
else:
print("Element is not present in the Hash Table")
return
def display(self):
print("\n")
for i in range(self.size):
print(str(i) + " = " + str(self.table[i]))

129
print("The number of element is the Table are : " +
str(self.elementCount))
table1 = hashTable()
table1.insert(89)
table1.insert(18)
table1.insert(49)
table1.insert(58)
table1.insert(9)
table1.display()
print()
print("The position of element 9 is : " + str(table1.search(9)))
print("The position of element 58 is : " + str(table1.search(58)))
print("\nTotal number of comaprisons done for searching = " +
str(table1.comparisons))
print()
#table1.remove(90)
table1.remove(18)
table1.display()

130
OUTPUT:
Enter the Size of the hash table : 3
Element 89 at position 2
Element 18 at position 0
Element 49 at position 1
Hash Table Full
Hash Table Full

0 = 18
1 = 49
2 = 89
The number of element is the Table are : 3

Element not Found


The position of element 9 is : False
Element not Found
The position of element 58 is : False

Total number of comaprisons done for searching = 102

Element 18 is Deleted

131
0=0
1 = 49
2 = 89
The number of element is the Table are : 2

RESULT:
Thus the given program has been executed and verified successfully.

132
EX.NO:8(C)
IMPLEMENTATION OF HASH TABLES
DATE: HASHING WITH DOUBLE HASHING
C

AIM:
To write a program to implement Hashing with double hashing.
ALGORITHM:

 Start.
 Initialize hash Table with all elements 0
 Create a method that checks if the hash table is full or not
 Create a method that returns position for a given element
 Replace with hash function
 Create another method that returns position for a given element
 Create a method to resolve collision by double hashing method
o Start a loop to find the position and calculate new position
by double hashing
o If new position is empty then break out of loop and return
new Position
o Else, as the position is not empty increase i
 Create a method that inserts element inside the hash table
o Checking if the table is full
o Checking if the position is empty, if empty position found
, store the element
o Collision occurred, do double hashing
 Create a method that searches for an element in the table
 Returns position of element if found
 Else if element is not found at position returned hash function
and then search element using double hashing
o Start a loop to find the position and calculate new position
by double hashing
o If element at new position is equal to the required element
o Else, as the position is not empty increase i

133
 Create a method to remove an element from the table
 Create a method to display the hash table
 Stop.
PROGRAM:
class doubleHashTable:
def __init__ (self):
self.size = int(input("Enter the Size of the hash table : "))
self.num = 7
self.table = list(0 for i in range(self.size))
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
def h1(self, element):
return element % self.size
def h2(self, element):
return (self.num-(element % self.num))
def doubleHashing(self, element, position):
posFound = False
limit = 50

134
i=1
while i <= limit:
newPosition = (self.h1(element) + i*self.h2(element)) %
self.size
if self.table[newPosition] == 0:
posFound = True
break
else:
i += 1
return posFound, newPosition
def insert(self, element):
if self.isFull():
print("Hash Table Full")
return False
posFound = False
position = self.h1(element)
if self.table[position] == 0:
self.table[position] = element
print("Element " + str(element) + " at position " +
str(position))
isStored = True
self.elementCount += 1
else:

135
while not posFound:
print("Collision has occured for element " + str(element) + "
at position " + str(position) + " finding new Position.")
posFound, position = self.doubleHashing(element, position)
if posFound:
self.table[position] = element
self.elementCount += 1
return posFound
def search(self, element):
found = False
position = self.h1(element)
self.comparisons += 1
if(self.table[position] == element):
return position
else:
limit = 50
i=1
newPosition = position
while i <= limit:
position = (self.h1(element) + i*self.h2(element)) %
self.size
self.comparisons += 1
if self.table[position] == element :

136
found = True
break
elif self.table[position] == 0:
found = False
break
else:
# as the position is not empty increase i
i += 1
if found:
return position
else:
print("Element not Found")
return found
def remove(self, element):
position = self.search(element)
if position is not False:
self.table[position] = 0
print("Element " + str(element) + " is Deleted")
self.elementCount -= 1
else:
print("Element is not present in the Hash Table")
return

137
def display(self):
print("\n")
for i in range(self.size):
print(str(i) + " = " + str(self.table[i]))
print("The number of element is the Table are : " +
str(self.elementCount))
table1 = doubleHashTable()
table1.insert(89)
table1.insert(18)
table1.insert(49)
table1.insert(58)
table1.insert(9)
table1.display()
print()
print("The position of element 9 is : " + str(table1.search(9)))
print("The position of element 58 is : " + str(table1.search(58)))
print("\nTotal number of comaprisons done for searching = " +
str(table1.comparisons))
print()
table1.remove(18)
table1.display()

138
OUTPUT:
Enter the Size of the hash table : 4
Element 89 at position 1
Element 18 at position 2
Collision has occured for element 49 at position 1 finding new
Position.
Collision has occured for element 58 at position 2 finding new
Position.
Hash Table Full

0 = 49
1 = 89
2 = 18
3 = 58
The number of element is the Table are : 4

Element not Found


The position of element 9 is : False
The position of element 58 is : 3

Total number of comaprisons done for searching = 53

Element 18 is Deleted

139
0 = 49
1 = 89
2=0
3 = 58
The number of element is the Table are : 3

RESULT:
Thus the given program has been executed and verified successfully.

140
EX.NO:9(A)
TREE REPRESENTATION AND TRAVERSAL
DATE: ALGORITHM-ARRAY REPRESENTATION

AIM:
To write a program to implement tree using Array representation.
ALGORITHM:

 Start.
 Initialize the array with size numbering starting from 0 to n-1.
 Create a root method to set a root value
 if the array is not none, then print tree already had root
 Else, set the element as root
 Create a left method for to create left child
 If the array is none, then print no parent node is found
 Else, create a node as left child
 Create a Right method for to create right child
 If the array is none, then print no parent node is found
 Else, create a node as right child
 Display the nodes
 Stop.

141
PROGRAM:
tree = [None] * 20
def root(key):
if tree[0] != None:
print("Tree already had root")
else:
tree[0] = key
def set_left(key, parent):
if tree[parent] == None:
print("Can't set child at", (parent * 2) + 1, ", no parent found")
else:
tree[(parent * 2) + 1] = key
def set_right(key, parent):
if tree[parent] == None:
print("Can't set child at", (parent * 2) + 2, ", no parent found")
else:
tree[(parent * 2) + 2] = key
def print_tree():
for i in range(20):
if tree[i] != None:
print(tree[i], end="")
else:

142
print("-", end="")
# print()
root('3')
set_left('5', 0)
set_right('9', 0)
set_left('6', 1)
set_right('8', 1)
set_left('20', 2)
set_right('10', 2)
set_left('9', 5)
print_tree()

143
OUTPUT:
359682010----9--------

RESULT:
Thus the given program has been executed and verified successfully.
144
EX.NO:9(B)
TREE REPRESENTATION AND TRAVERSAL
DATE: ALGORITHM-LINKEDLIST REPRESENTATION

AIM:
To write a program to implement tree using linked list representation.
ALGORITHM:

 Start.
 Create a class and represent a node of binary tree
 Assign data to the new node, set left and right children to None
 Create a class and represent the root of binary tree
 Create a new node and check whether tree is empty ,add root to
the queue
 If node has both left and right child, add both the child to queue
 If node has no left child, make newNode as left child
 If node has left child but no right child, make newNode as right
child
 Display the list of nodes in binary tree
 Stop.

145
PROGRAM:
class Node:
def __init__ (self,data):
self.data = data;
self.left = None;
self.right = None;
class BinaryTree:
def __init__ (self):
self.root = None;
def insertNode(self, data):
newNode = Node(data);
if(self.root == None):
self.root = newNode;
return;
else:
queue = [];
queue.append(self.root);
while(True):
node = queue.pop(0);
if(node.left != None and node.right != None):
queue.append(node.left);
queue.append(node.right);

146
else:
if(node.left == None):
node.left = newNode;
queue.append(node.left);
else:
node.right = newNode;
queue.append(node.right);
break;
def inorderTraversal(self, node):
#Check whether tree is empty
if(self.root == None):
print("Tree is empty");
return;
else:
if(node.left != None):
self.inorderTraversal(node.left);
print(node.data),
if(node.right!= None):
self.inorderTraversal(node.right);
bt = BinaryTree();
bt.insertNode(1);
print("Binary tree after insertion");

147
bt.inorderTraversal(bt.root);
bt.insertNode(2);
bt.insertNode(3);
print("\nBinary tree after insertion");
bt.inorderTraversal(bt.root);
bt.insertNode(4);
bt.insertNode(5);
print("\nBinary tree after insertion");
bt.inorderTraversal(bt.root);
bt.insertNode(6);
bt.insertNode(7);
print("\nBinary tree after insertion");
bt.inorderTraversal(bt.root);

148
OUTPUT:
Binary tree after insertion
1

Binary tree after insertion


2
1
3

Binary tree after insertion


4
2
5
1
3

Binary tree after insertion


4
2
5
1
6

149
3
7

RESULT:
Thus the given program has been executed and verified successfully.

150
EX.NO:9(C) TREE REPRESENTATION AND TRAVERSAL
DATE: ALGORITHM-TRAVERSAL ALGORITHM

AIM:
To write a program to implement traversal algorithm.
ALGORITHM:

 Start.
 Create a class and represent a node
 Assign data to the new node, set left and right children to None
 If tree is non empty, create a new node and compare to current
node
 If new node less than current node, then make it as left child of
current node
 If new node greater than current node, then make it as right
child of current node
 Else, if tree is empty ,add node to the root node
 Create inorder method, then recursively traverse left,root, right
order
 Create preorder method, then recursively traverse root, left,right
order
 Create postorder method, then recursively traverse left,right,root
order
 Display all nodes
 Stop.

151
PROGRAM:
class Node:
def __init__ (self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
152
print( self.data),
if self.right:
self.right.PrintTree()
def inorderTraversal(self, root):
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
return res
def PreorderTraversal(self, root):
res = []
if root:
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
return res
def PostorderTraversal(self, root):
res = []
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)

153
res.append(root.data)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.inorderTraversal(root))
print(root.PreorderTraversal(root))
print(root.PostorderTraversal(root))

154
OUTPUT:
[10, 14, 19, 27, 31, 35, 42]
[27, 14, 10, 19, 35, 31, 42]
[10, 19, 14, 31, 42, 35, 27]

RESULT:
Thus the given program has been executed and verified successfully.

155
EX.NO:10(a)
DATE: BINARY SEARCH TREE

AIM:
To write a program to implement binary search tree.
ALGORITHM:

 Start.
 Insert node into the tree as the root of the tree.
 Read the next element, if it is lesser than the root node element,
insert it as the root of the left sub- tree.
 Otherwise, insert it as the root of the right of the right sub-tree
 Compare the element with the root of the tree.
 If the item is matched then return the location of the node.
 Otherwise check if item is less than the element present on root,
if so then move to the left sub-tree.
 If not, then move to the right sub-tree.
 Repeat this procedure recursively until match found.
 If element is not found then return NULL.
 Find the data of the node to be deleted.
 If the node is a leaf node, delete the node directly.
 Else if the node has one child, copy the child to the node to be
deleted and delete the child node.
 Else if the node has two children, find the inorder successor of
the node.
 Copy the contents of the inorder successor to the node to be
deleted and delete the inorder successor.
 Stop.

156
PROGRAM:
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def inorder(root):
if root is not None:
inorder(root.left)
print(str(root.key) + "->", end=' ')
inorder(root.right)
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
def minValueNode(node):
current = node
while(current.left is not None):

157
current = current.left
return current
def deleteNode(root, key):
if root is None:
return root
if key < root.key:
root.left = deleteNode(root.left, key)
elif(key > root.key):
root.right = deleteNode(root.right, key)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = minValueNode(root.right)
root.key = temp.key
root.right = deleteNode(root.right, temp.key)
return root

158
root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 7)
root = insert(root, 10)
root = insert(root, 14)
root = insert(root, 4)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 4")
root = deleteNode(root, 4)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 6")
root = deleteNode(root, 6)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 3")
root = deleteNode(root, 3)
print("Inorder traversal: ", end=' ')

159
inorder(root)

OUTPUT:
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 10-> 14->
Delete 4
Inorder traversal: 1-> 3-> 6-> 7-> 8-> 10-> 14->
Delete 6
Inorder traversal: 1-> 3-> 7-> 8-> 10-> 14->
Delete 3
Inorder traversal: 1-> 7-> 8-> 10-> 14->

RESULT:
Thus the given program has been executed and verified successfully

160
EX.NO:10(B)
AVL TREE
DATE:

AIM:
To write a program to implement AVL tree.
ALGORITHM:

 Start.
 Create a class and represent a node
 Assign data to the new node, set left and right children to None
and set height is 1
 If tree is non empty, create a new node and compare to current
node
 If new node less than current node, then make it as left child of
current node
 If new node greater than current node, then make it as right
child of current node
 Else, if tree is empty ,add node to the root node
 After inserting the elements check the Balance Factor of each
node.
 If the balance factor of every node found like 0 or 1 or -1 then
the algorithm perform for the next operation.
 If the balance factor of any node comes other than the above
three values then the tree is imbalanced. Then perform rotation
to make it balanced and then the algorithm perform for the next
operation.
 Create a method to delete a node and find where the node is
stored
 If the node is a leaf node, delete the node directly.
 Else if the node has one child, copy the child to the node to be
deleted and delete the child node.

161
 Else if the node has two children, find the inorder successor of
the node.
 Copy the contents of the inorder successor to the node to be
deleted and delete the inorder successor.
 Again do step 8 and 9
 Display the preorder traversal
 Stop.
PROGRAM:
import sys
class TreeNode(object):
def __init__ (self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
class AVLTree(object):
def insert_node(self, root, key):
if not root:
return TreeNode(key)
elif key < root.key:
root.left = self.insert_node(root.left, key)
else:
root.right = self.insert_node(root.right, key)
root.height = 1 + max(self.getHeight(root.left),

162
self.getHeight(root.right))
balanceFactor = self.getBalance(root)
if balanceFactor > 1:
if key < root.left.key:
return self.rightRotate(root)
else:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
if balanceFactor < -1:
if key > root.right.key:
return self.leftRotate(root)
else:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
def delete_node(self, root, key):
if not root:
return root
elif key < root.key:
root.left = self.delete_node(root.left, key)
elif key > root.key:
root.right = self.delete_node(root.right, key)

163
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = self.getMinValueNode(root.right)
root.key = temp.key
root.right = self.delete_node(root.right,temp.key)
if root is None:
return root
root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
balanceFactor = self.getBalance(root)
if balanceFactor > 1:
if self.getBalance(root.left) >= 0:
return self.rightRotate(root)
else:
root.left = self.leftRotate(root.left)

164
return self.rightRotate(root)
if balanceFactor < -1:
if self.getBalance(root.right) <= 0:
return self.leftRotate(root)
else:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
def leftRotate(self, z):
y = z.right
T2 = y.left
y.left = z
z.right = T2
z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right))
return y
def rightRotate(self, z):
y = z.left
T3 = y.right
y.right = z
z.left = T3
z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right))

165
y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right))
return y
def getHeight(self, root):
if not root:
return 0
return root.height
def getBalance(self, root):
if not root:
return 0
return self.getHeight(root.left) - self.getHeight(root.right)
def getMinValueNode(self, root):
if root is None or root.left is None:
return root
return self.getMinValueNode(root.left)
def preOrder(self, root):
if not root:
return
print("{0} ".format(root.key), end="")
self.preOrder(root.left)
self.preOrder(root.right)
def printHelper(self, currPtr, indent, last):
if currPtr != None:

166
sys.stdout.write(indent)
if last:
sys.stdout.write("R--- ")
indent += " "
else:
sys.stdout.write("L --- ")
indent += "| "
print(currPtr.key)
self.printHelper(currPtr.left, indent, False)
self.printHelper(currPtr.right, indent, True)
myTree = AVLTree()
root = None
nums = [15,20,24,10,13,7,30,36,25]
for num in nums:
root = myTree.insert_node(root, num)
myTree.printHelper(root, "", True)
key = 24
root = myTree.delete_node(root, key)
print("After Deletion: ")
myTree.printHelper(root, "", True)
key = 20
root = myTree.delete_node(root, key)

167
print("After Deletion: ")
myTree.printHelper(root, "", True)
key = 15
root = myTree.delete_node(root, key)
print("After Deletion: ")
myTree.printHelper(root, "", True)

OUTPUT:
R--- 13
L --- 10
| L --- 7
R--- 24
L --- 20
| L --- 15
R--- 30
L --- 25
R--- 36
After Deletion:
R--- 13
L --- 10
| L --- 7
R--- 25

168
L --- 20
| L --- 15
R--- 30
R--- 36
After Deletion:
R--- 13
L --- 10
| L --- 7
R--- 25
L --- 15
R--- 30
R--- 36
After Deletion:
R--- 13
L --- 10
| L --- 7
R--- 30
L --- 25
R--- 36

169
RESULT:
Thus the given program has been executed and verified successfully.

170
EX.NO:11(A)
IMPLEMENTATION OF HEAPS
DATE: MAX HEAP

AIM:
To write an program to implement max heap.
ALGORITHM:

 Start.
 Use an array to store the data.
 Start storing from index 1, not 0.
 Create a insert method and find the size of the array
 If the size is 0, then append the value
 Else, append the value and set the range for heapify function
 For any given node at position i:
 If it is Left Child then l= [2*i+1]
 If it is Right Child then r= [2*i+2]
 Then find the maximum value and swap the position
 Create delete method and delete the root node
 Swap the position
 Stop

171
PROGRAM:
def heapify(arr, n, i):
largest = i
l=2*i+1
r=2*i+2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def insert(array, newNum):
size = len(array)
if size == 0:
array.append(newNum)
else:
array.append(newNum);
for i in range((size//2)-1, -1, -1):
heapify(array, size, i)
def deleteNode(array, num):
size = len(array)

172
i=0
for i in range(0, size):
if num == array[i]:
break
array[i], array[size-1] = array[size-1], array[i]
array.remove(num)
for i in range((len(array)//2)-1, -1, -1):
heapify(array, len(array), i)
arr = []
insert(arr, 35)
insert(arr, 33)
insert(arr, 42)
insert(arr, 10)
insert(arr, 14)
insert(arr, 19)
insert(arr, 27)
insert(arr, 44)
insert(arr, 26)
print ("Max-Heap array: " + str(arr))
deleteNode(arr, 44)
print("After deleting an element: " + str(arr))
deleteNode(arr, 33)

173
print("After deleting an element: " + str(arr))

OUTPUT:
Max-Heap array: [44, 42, 35, 33, 14, 19, 27, 10, 26]
After deleting an element: [42, 33, 35, 26, 14, 19, 27, 10]
After deleting an element: [42, 26, 35, 10, 14, 19, 27]

RESULT:
Thus the given program has been executed and verified successfully.

174
EX.NO:11(B)
IMPLEMENTATION OF HEAPS
DATE:
MIN HEAP

AIM:
To write an program to implement min heap.
ALGORITHM:

 Start.
 Use an array to store the data.
 Start storing from index 1, not 0.
 Create a insert method and find the size of the array
 If the size is 0, then append the value
 Else, append the value and set the range for heapify function
 For any given node at position i:
 If it is Left Child then l= [2*i+1]
 If it is Right Child then r= [2*i+2]
 Then find the minimum value and swap the position
 Create delete method and delete the root node
 Swap the position
 Stop

175
PROGRAM:
def min_heapify(A,k):
l = left(k)
r = right(k)
if l < len(A) and A[l] < A[k]:
smallest = l
else:
smallest = k
if r < len(A) and A[r] < A[smallest]:
smallest = r
if smallest != k:
A[k], A[smallest] = A[smallest], A[k]
min_heapify(A, smallest)
def left(k):
return 2 * k + 1
def right(k):
return 2 * k + 2
def build_min_heap(A):
n = int((len(A)//2)-1)
for k in range(n, -1, -1):
min_heapify(A,k)
A = [3,9,2,1,4,5]
build_min_heap(A)
176
print(A)

OUTPUT:
[1, 3, 2, 9, 4, 5]

RESULT:
Thus the given program has been executed and verified successfully.

177
EX.NO:12(A) GRAPH REPRESENTATION AND TRAVERSAL
DATE: ALGORITHM
GRAPH REPRESENTATION—ADJACENCY LIST

AIM:
To write a program to implement graph representation using
Adjacency Matrix .
ALGORITHM:

 Start.
 Create an array of size and type of array must be list of vertices
 Each array element is initialize with empty list
 Create a add edge method to store v in list
 Iterate each given edge of the form (u,v)
 Append v to the uth list of array
 Stop.

178
PROGRAM:
class AdjNode:
def __init__ (self, data):
self.vertex = data
self.next = None
class Graph:
def __init__ (self, vertices):
self.V = vertices
self.graph = [None] * self.V
def add_edge(self, src, dest):
node = AdjNode(dest)
node.next = self.graph[src]
self.graph[src] = node
node = AdjNode(src)
node.next = self.graph[dest]
self.graph[dest] = node
def print_graph(self):
for i in range(self.V):
print("Adjacency list of vertex {}\n head".format(i), end="")
temp = self.graph[i]
while temp:
print(" -> {}".format(temp.vertex), end="")

179
temp = temp.next
print(" \n")
if __name__ == "__main__":
V=5
graph = Graph(V)
graph.add_edge(0, 1)
graph.add_edge(0, 4)
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(1, 4)
graph.add_edge(2, 3)
graph.add_edge(3, 4)
graph.print_graph()

180
OUTPUT:
Adjacency list of vertex 0
head -> 4 -> 1

Adjacency list of vertex 1


head -> 4 -> 3 -> 2 -> 0

Adjacency list of vertex 2


head -> 3 -> 1

Adjacency list of vertex 3


head -> 4 -> 2 -> 1

Adjacency list of vertex 4


head -> 3 -> 1 -> 0

181
RESULT:
Thus the given program has been executed and verified successfully.

182
EX.NO:12(B)
GRAPH REPRESENTATION AND TRAVERSAL
DATE: ALGORITHM
GRAPH REPRESENTATION—ADJACENCY MATRIX

AIM:
To write a program to implement graph representation using
Adjacency matrix.
ALGORITHM:

 Start.
 Create a matrix of size N*N
 Initialise it with zero
 Iterate over each edge of the form(u,v)
 Assign 1 to matix[u][v]
 Checks if the vertex exists in the graph
 Checks if the vertex is connecting to itself
 Else, connecting the vertices
 Define a remove function
 Check the vertex is already present
 Else, remove the vertex
 Stop.

183
PROGRAM:
class Graph:
n=0
g =[[0 for x in range(10)] for y in range(10)]
def __init__ (self, x):
self. n = x
for i in range(0, self. n):
for j in range(0, self. n):
self. g[i][j]= 0
def displayAdjacencyMatrix(self):
print("\n\n Adjacency Matrix:", end ="")
for i in range(0, self. n):
print()
for j in range(0, self. n):
print("", self. g[i][j], end ="")
def addEdge(self, x, y):
if(x>= self. n) or (y >= self. n):
print("Vertex does not exists !")
if(x == y):
print("Same Vertex !")
else:
self. g[y][x]= 1

184
self. g[x][y]= 1
def addVertex(self):
self. n = self. n + 1;
for i in range(0, self. n):
self. g[i][self. n-1]= 0
self. g[self. n-1][i]= 0
def removeVertex(self, x):
if(x>self. n):
print("Vertex not present !")
else:
while(x<self. n):
for i in range(0, self. n):
self. g[i][x]= self. g[i][x + 1]
for i in range(0, self. n):
self. g[x][i]= self. g[x + 1][i]
x=x+1
self. n = self. n - 1
obj = Graph(4);
obj.addEdge(0, 1);
obj.addEdge(0, 2);
obj.addEdge(1, 2);
obj.addEdge(2, 3);

185
obj.displayAdjacencyMatrix();
obj.displayAdjacencyMatrix();
obj.removeVertex(1);
obj.displayAdjacencyMatrix();

186
OUTPUT:
Adjacency Matrix:
0110
1010
1101
0010

Adjacency Matrix:
0110
1010
1101
0010

Adjacency Matrix:
010
101
010

187
RESULT:
Thus the given program has been executed and verified successfully.

188
EX.NO:12(C) GRAPH REPRESENTATION AND TRAVERSAL
DATE: ALGORITHM
TRAVERSAL ALGORITHM—BFS

AIM:
To write a program to implement graph traversal algorithm using
BFS.
ALGORITHM:

 Start.
 Start by putting any one of the graph Vertices at the back of a
queue.
 Take the front item of the queue and add it to the visited list.
 Create a list of that vertex’s adjacent nodes.Add the ones which
aren’t in the visited list to the back of the queue.
 Keep repeating steps 2 and 3 until the queue is empty
 Stop.

189
PROGRAM:
graph = {'5' : ['3','7'],'3' : ['2', '4'],'7' : ['8'],'2' : [],'4' : ['8'],'8' : []}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')

190
OUTPUT:
Following is the Breadth-First Search
537248

PROGRAM 2:
graph = {'A': ['B', 'C', 'E'],'B': ['A','D', 'E'],'C': ['A', 'F', 'G'], 'D':
['B'],'E': ['A', 'B','D'], 'F': ['C'],'G': ['C']}
def bfs_connected_component(graph, start):
explored = []
queue = [start]
while queue:
node = queue.pop(0)
if node not in explored:
explored.append(node)
neighbours = graph[node]
for neighbour in neighbours:
queue.append(neighbour)
return explored
explored=bfs_connected_component(graph,'A')
print(explored)

191
OUTPUT:
['A', 'B', 'C', 'E', 'D', 'F', 'G']

RESULT:
Thus the given program has been executed and verified successfully.

192
EX.NO:12(D) GRAPH REPRESENTATION AND TRAVERSAL
DATE: ALGORITHM
TRAVERSAL ALGORITHM—DFS

AIM:
To write a program to implement graph traversal algorithm using
DFS.
ALGORITHM:

 Start.
 Create a recursive function that takes the index of the node and a
visited array.
 Mark the current node as visited and print the node.
 Traverse all the adjacent and unmarked nodes and call the
recursive function with the index of the adjacent node.
 Run a loop from 0 to the number of vertices and check if the
node is unvisited in the previous DFS, call the recursive
function with the current node.
 Stop.

193
PROGRAM:
def recursive_dfs(graph, source,path = []):
if source not in path:
path.append(source)
if source not in graph:
return path
for neighbour in graph[source]:
path = recursive_dfs(graph, neighbour, path)
return path
graph = {"A":["B","C", "D"],
"B":["E"],"C":["F","G"],"D":["H"],"E":["I"],"F":["J"]}
path = recursive_dfs(graph, "A")
print("DFS")
print(" ".join(path))

194
OUTPUT:
DFS
ABEICFJGDH

RESULT:
Thus the given program has been executed and verified successfully.

195
EX.NO:13
DATE: SINGLE SOURCE SHORTEST PATH ALGORITHM

AIM:
To write a program to implement single source shortest path
algorithm.
ALGORITHM:

 Start.
 Start with a weighted graph
 Choose a starting vertex and assign infinity path values to all
other vertices
 Go to each vertex and update its path length
 If the path length of the adjacent vertex is lesser than new path
length, don’t update it
 Avoid updating path length of already visited vertices
 After each iteration pick the unvisited vertiex with the least path
length
 Repeat until all verties have been visited
 Stop.

196
PROGRAM:
import heapq
def calculate_distances(graph, starting_vertex):
distances = {vertex: float('infinity') for vertex in graph}
distances[starting_vertex] = 0
pq = [(0, starting_vertex)]
while len(pq) > 0:
current_distance, current_vertex = heapq.heappop(pq)
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
example_graph = {'v1': {'v2': 2, 'v4': 1,},'v2': {'v4': 3, 'v5': 10,},'v3':
{'v1': 4,},'v4': {'v3': 2, 'v6': 8, 'v7': 4,'v5': 2},'v5': {'v7': 6,},'v6': {'v3':
5,},'v7': {'v6': 1,},}
print(calculate_distances(example_graph, 'v1'))

197
OUTPUT:
{'v1': 0, 'v2': inf, 'v3': 15, 'v4': 1, 'v5': 3, 'v6': 10, 'v7': 9}

RESULT:
Thus the given program has been executed and verified successfully.

198
EX.NO:14(A)
MINIMUM SPANNING TREE
DATE:
KRUSKAL’S ALGORITHM

AIM:
To write a program to implement minimum spanning tree using
Kruskal’s algorithm.
ALGORITHM:

 Start.
 Sort all the edges in non-decreasing order of their weight.
 Pick the smallest edge.
 Check if it forms a cycle with the spanning tree formed so far.
 If cycle is not formed, include this edge. Else, discard it.
 Repeat step2 until there are (V-1) edges in the spanning tree.
 Stop.

199
PROGRAM:
class Edge :
def __init__ (self, arg_src, arg_dst, arg_weight) :
self.src = arg_src
self.dst = arg_dst
self.weight = arg_weight
class Graph :
def __init__ (self, arg_num_nodes, arg_edgelist) :
self.num_nodes = arg_num_nodes
self.edgelist = arg_edgelist
self.parent = []
self.rank = []
self.mst = []
def FindParent (self, node) :
if node != self.parent[node] :
self.parent[node] = self.FindParent(self.parent[node])
return self.parent[node]
def KruskalMST (self) :
self.edgelist.sort(key = lambda Edge : Edge.weight)
self.parent = [None] * self.num_nodes
self.rank = [None] * self.num_nodes
for n in range(self.num_nodes) :

200
self.parent[n] = n
self.rank[n] = 0
for edge in self.edgelist :
root1 = self.FindParent(edge.src)
root2 = self.FindParent(edge.dst)
if root1 != root2 :
self.mst.append(edge)
if self.rank[root1] < self.rank[root2] :
self.parent[root1] = root2
self.rank[root2] += 1
else :
self.parent[root2] = root1
self.rank[root1] += 1
print("\nEdges of minimum spanning tree in graph :", end=' ')
cost = 0
for edge in self.mst :
print("[" + str(edge.src) + "-" + str(edge.dst) + "](" +
str(edge.weight) + ")", end = ' ')
cost += edge.weight
print("\nCost of minimum spanning tree : " +str(cost))
def main() :
num_nodes = 5
e1 = Edge(0, 1, 5)
201
e2 = Edge(0, 3, 6)
e3 = Edge(1, 2, 1)
e4 = Edge(1, 3, 3)
e5 = Edge(2, 3, 4)
e6 = Edge(2, 4, 6)
e7 = Edge(3, 4, 2)
g1 = Graph(num_nodes, [e1, e2, e3, e4, e5, e6, e7])
g1.KruskalMST()
if __name__ == "__main__" :
main()

202
OUTPUT:

Edges of minimum spanning tree in graph : [1-2](1) [3-4](2) [1-3](3)


[0-1](5)
Cost of minimum spanning tree : 11

RESULT:
Thus the given program has been executed and verified successfully.

203
EX.NO:14(B)
MINIMUM SPANNING TREE
DATE:
PRIM’SALGORITHM

AIM:
To write a program to implement minimum spanning tree using
Prim’s algorithm.
ALGORITHM:

 Start.
 Start at any node in the list
 Choose a starting vertex is visited and assign all other vertices
are unvisited
 Find an edges e with minimum cost
 Add the edge e found in previous to the spanning tree and
change the edge as visited
 Repeat the step 2 and 3 until all nodes become visited
 Stop

204
PROGRAM:
INF = 9999999
V=7
G = [[0, 2, 4, 1, 0, 0, 0],
[2, 0, 0, 3, 7, 0, 0],
[4, 0, 0, 2, 0, 5, 0],
[1, 3, 2, 0, 7, 8, 4],
[0, 7, 0, 7, 0, 0, 6],
[0, 0, 5, 8, 0, 0, 1],
[0, 0, 0, 4, 6, 1, 0]]
selected = [0, 0, 0, 0, 0, 0, 0]
no_edge = 0
selected[0] = True
print("Edge : Weight\n")
while (no_edge < V - 1):
minimum = INF
x=0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):

205
if minimum > G[i][j]:
minimum = G[i][j]
x=i
y=j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1

206
OUTPUT:
Edge : Weight

0-3:1
0-1:2
3-2:2
3-6:4
6-5:1
6-4:6

RESULT:
Thus the given program has been executed and verified successfully.

207
208

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy