0% found this document useful (0 votes)
10 views93 pages

Dsa - Copy-41-133

Uploaded by

februarymeenu
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)
10 views93 pages

Dsa - Copy-41-133

Uploaded by

februarymeenu
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/ 93

Ex.

No:5a Implementation of Stack Using Linked List


Date:
Aim:

To write a python program to implement stack using linked list

Algorithm:

1. Create a two class, class Node and Class Stack

2. Allocate memory to create a newNode with given value and name it as NEW_NODE.

3. Check whether TOP == NULL of Stack

4. If TOP == NULL means empty, then set newNode → next = NULL and TOP =
NEW_NODE.
5. If TOP != NULL, then set newNode → next = top and TOP = NEW_NODE.

6. Check whether TOP == NULL of Stack.


7. If TOP == NULL then print “Stack is Empty” and terminate the function
8. If TOP != NULL, then define a Node pointer ‘temp’ and set it to ‘top’.
9. Then set ‘top = top → next’.
10. Finally, delete ‘temp’. (free(temp)).

11. Check whether TOP == NULL of Stack.


12. If TOP == NULL then print “Stack is Empty” and terminate the function
13. If TOP != NULL, then display top->data.

14. Check whether TOP == NULL of Stack.


15. If TOP == NULL then print “Stack is Empty” and terminate the function
16. If TOP != NULL, then define a Node pointer ‘ptr’ and initialize with top.
17. Display ‘temp → data’ util temp → next != NULL.
18. Finally Display ‘temp → data’

Program:

class Node:
def init (self, data=None, next=None):
self.data = data
self.next = next
class Stack:
def init (self):
self.top = None
self.size=0
def push(self, data):
if self.top is None:
self.top = Node(data, None)
self.size += 1
return
self.top = Node(data, self.top)
self.size += 1
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
self.size -= 1
return temp.data
def getSize(self):
return self.size
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(30)
stack.push(40)
print("List of elements in stack:")
stack.display()
print("The size of the stack is:",stack.getSize())
print("The top of the element is:",stack.peek())
print("The popped element from the stack:" ,stack.pop())
print("The size of the stack is:",stack.getSize())
stack.display()
print(stack.emptystack())
stack.clearstack()
print(stack.emptystack())
Output:

Result:
Ex.No:5b Implementation of Queue Using Linked List
Date:
Aim:

To write a python program to implement queue using linked list

Algorithm:

1. Create a two class, class Node and Class Queue


2. Define a 'Node' structure with two members data and next.

3. Define two Node pointers 'front' and 'rear' and set both to NULL.

4. Create a newNode with given value and set 'newNode → next' to NULL.

5. Check whether queue is Empty (rear == NULL)

6. If it is Empty then, set front = newNode and rear = newNode.

7. If it is Not Empty then, set rear → next = newNode and rear = newNode

8. Check whether queue is Empty (front == NULL).

9. If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and terminate from the
function

10. If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.

11. Then set 'front = front → next' and delete 'temp' (free(temp)).

12. Check whether queue is Empty (front == NULL).

13. If it is Empty then, display 'Queue is Empty!!!' and terminate the function.

14. If it is Not Empty then, define a Node pointer 'temp' and initialize with front.

15. Display 'temp → data --->' and move it to the next node. Repeat the same until 'temp' reaches to 'rear'
(temp → next != NULL).

16. Finally! Display 'temp → data ---> NULL'.


Program:

class Node:
def init (self, data, left=None, right=None):
self.data = data
self.next = None
class Queue:
def init (self):
self.rear = None
self.front = None
self.count = 0
def dequeue(self):
if self.front is None:
print('Queue Underflow')
exit(-1)
temp = self.front
print('Removing…', temp.data)
self.front = self.front.next
if self.front is None:
self.rear = None
self.count -= 1
return temp.data

def enqueue(self, item):


node = Node(item)
print('Inserting…', item)
if self.front is None:
self.front = node
self.rear = node
else:
self.rear.next = node
self.rear = node
self.count += 1
def peek(self):
if self.front:
return self.front.data
else:
exit(-1)
def isEmpty(self):
return self.rear is None and self.front is None
def size(self):
return self.count
if name == ' main ':
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
print('The front element is', q.peek())
q.dequeue()
q.dequeue()
q.dequeue()
#q.dequeue()
if q.isEmpty():
print('The queue is empty')
else:
print('The queue is not empty')
print("The size of the queue is",q.size())

Output:

Result:
Ex.No:6a Implementation of Polynomial Manipulation Using List
Date:
Aim:

To write a python program to implement polynomial manipulation using list

Algorithm:

1. Create a two class, class Node and Class Queue


2. Define a 'Node' structure with three members data, power and next.

3. Define a Node pointer head and set both to NULL

4. Create a newNode with given value and insert the node, when the list is empty
5. If the list in not empty, compare the new node with the existing node

If the power value of newnode is greater than existing node, then insert the node as head element

Else, if the power value of newnode is smaller than existing node, then insert the node as next
element

If the power value of newnode is equal to existing node, then add the power value of existing node and
new node, insert the node

6. Create a function AddTwoPolynomial(), to add the two polynomial equation

7. Define a two variable first and second and make the first = self.head , second = other.head

8. Check the power value of two variables, if it is equal, then add the power value and coefficient, then
insert the newnode in equation

9. Else, insert the node in the equation

10. Create the display method to print the values of both equation
Program:

class Node :
def init (self, data, power) :
self.data = data
self.power = power
self.next = None
def updateRecord(self, data, power) :
self.data = data
self.power = power
class AddPolynomial :
def init (self) :
self.head = None
def display(self) :
if (self.head == None) :
print("Empty Polynomial ")
print(" ", end = "")
temp = self.head

while (temp != None) :


if (temp != self.head) :
print("+", temp.data, end = "")
else :
print(temp.data, end = "")
if (temp.power != 0) :
print("x^", temp.power, end = " ",sep = "")
temp = temp.next
print(end = "\n")
def addNode(self, data, power) :
if (self.head == None) :
self.head = Node(data, power)
else :
node = None
temp = self.head
location = None
while (temp != None and temp.power >= power) :
location = temp
temp = temp.next
if (location != None and location.power == power) :
location.data = location.data + data
else :
node = Node(data, power)
if (location == None) :
node.next = self.head
self.head = node
else :
node.next = location.next

location.next = node
def addTwoPolynomials(self, other) :
result = None
tail = None
node = None
first = self.head
second = other.head
while (first != None or second != None) :
node = Node(0, 0)
if (result == None) :
result = node
if (first != None and second != None) :
if (first.power == second.power) :
node.updateRecord(first.data + second.data, first.power)
first = first.next
second = second.next
elif (first.power > second.power) :
node.updateRecord(first.data, first.power)
first = first.next
else :
node.updateRecord(second.data, second.power)
second = second.next
elif (first != None) :
node.updateRecord(first.data, first.power)
first = first.next
else :
node.updateRecord(second.data, second.power)
second = second.next
if (tail == None) :
tail = node
else :
tail.next = node
tail = node
return result
def main() :
poly1 = AddPolynomial()
poly2 = AddPolynomial()
result = AddPolynomial()
poly1.addNode(9, 3)
poly1.addNode(4, 2)
poly1.addNode(3, 0)
poly1.addNode(7, 1)
poly1.addNode(3, 4)
poly2.addNode(7, 3)
poly2.addNode(4, 0)
poly2.addNode(6, 1)
poly2.addNode(1, 2)
print("Polynomial A")
poly1.display()
print(" Polynomial B")
poly2.display()
result.head = poly1.addTwoPolynomials(poly2)
print(" Result")
result.display()
if name == " main ": main()
Output

Result:
Ex.No:6b Implementation of Infix to Postfix Conversion Using Stack
Date:
Aim:
To write a python program to implement infix to postfix using stack
Algorithm
Step 1 : Scan the Infix Expression from left to right.
Step 2 : If the scanned character is an operand, append it with final Infix to Postfix string.
Step 3 : Else,
Step 3.1 : If the precedence order of the scanned(incoming) operator is greater than
the precedence order of the operator in the stack (or the stack is empty or the stack contains
a ‘(‘ or ‘[‘ or ‘{‘), push it on stack.
Step 3.2 : 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 you encounter parenthesis while popping then stop there and push
the scanned operator in the stack.)
Step 4 : If the scanned character is an ‘(‘ or ‘[‘ or ‘{‘, push it to the stack.
Step 5 : If the scanned character is an ‘)’or ‘]’ or ‘}’, pop the stack and and output it until a
‘(‘ or ‘[‘ or ‘{‘ respectively is encountered, and discard both the parenthesis.
Step 6 : Repeat steps 2-6 until infix expression is scanned.
Step 7 : Print the output
Step 8 : Pop and output from the stack until it is not empty.
Program:
class infix_to_postfix:
precedence={'^':5,'*':4,'/':4,'+':3,'-':3,'(':2,')':1}
def init (self):
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isempty():
return 0
else:
self.size-=1
return self.items.pop()
def isempty(self):
if(self.size==-1):
return True
else:
return False
def seek(self):
if self.isempty():
return false
else:
return self.items[self.size]
def isOperand(self,i):
if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
return True
else:
return False
def infixtopostfix (self,expr):
postfix=""
print('postfix expression after every iteration is:')
for i in expr:
if(len(expr)%2==0):
print("Incorrect infix expr")
return False
elif(self.isOperand(i)):
postfix +=i
elif(i in '+-*/^'):
while(len(self.items)and self.precedence[i]<=self.precedence[self.seek()]):
postfix+=self.pop()
self.push(i)
elif i is '(':
self.push(i)
elif i is ')':
o=self.pop()
while o!='(':
postfix +=o
o=self.pop()
print(postfix)
#end of for
while len(self.items):
if(self.seek()=='('):
self.pop()
else:
postfix+=self.pop()
return postfix
s=infix_to_postfix()
expr=input('enter the expression ')
result=s.infixtopostfix(expr)
if (result!=False):
print("the postfix expr of :",expr,"is",result)

Output:

Result
Ex.No:6c Implementation of Queue Using Stack
Date:
Aim:

To write a python program to implement Queue using Stack

Algorithm:

1. Create a two class, Class Stack and Class Queue


2. Define a 'Node' structure with two members inbox and outbox. These two members are used to call
tha class Stack

3. Create the list item[] and insert the insert elements by using stack on queue

4. Insert the elements in queue using push()

5. Remove the element from queue using pop()

6. Perform queue operation based on stack operation

7. Display the elements in stack

Program:

class Queue:
def init (self):
self.inbox = Stack()
self.outbox = Stack()
def is_empty(self):
return (self.inbox.is_empty() and self.outbox.is_empty())
def enqueue(self, data):
self.inbox.push(data)
def dequeue(self):
if self.outbox.is_empty():
while not self.inbox.is_empty():
popped = self.inbox.pop()
self.outbox.push(popped)
return self.outbox.pop()
class Stack:
def init (self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
a_queue = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
a_queue.enqueue(int(do[1]))
elif operation == 'dequeue':
if a_queue.is_empty():
print('Queue is empty.')
else:
dequeued = a_queue.dequeue()
print('Dequeued element: ', int(dequeued))
elif operation == 'quit':
break
Output:

Result
Ex.No:7a Implementation of Bubble Sort Algorithm
Date:
Aim:

To write a program to implement Bubble sort algorithm

Algorithm

1. Get the total number of items in the given list


2. Determine the number of outer passes (n - 1) to be done. Its length is list minus one
3. 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
4. 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.
5. Return the result when all passes have been done. Return the results of the sorted list

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]

arr = list()

n=int(input("Enter the Size of the List:"))

for i in range(n):

arr.append(int(input("Enter the element:")))

print ("The array is:",arr)

bubbleSort(arr)

print ("Sorted array is:",arr)


Output:

Result:
Ex.No:7b Implementation of Selection Sort
Date: Algorithm

Aim:

To write a program to implement selection sort algorithm

Algorithm:

1. Get the value of n which is the total size of the array


2. Partition the list into sorted and unsorted sections. The sorted section is initially empty
while the unsorted section contains the entire list
3. Pick the minimum value from the unpartitioned section and placed it into the sorted
section.
4. Repeat the process (n – 1) times until all of the elements in the list have been sorted.

Program:

arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
arr.append(int(input("Enter the element:")))
print ("The array is:",arr)
for i in range(0,n):
j=i+1
for j in range(j, n):
if arr[i] > arr[j]:
arr[i] ,arr[j] =arr[j] ,arr[i]
print ("Sorted array is:",arr)
Output:

Result:
Ex.No:7c Implementation of Insertion Sort Algorithm
Date:
Aim:

To write a program to implement insertion sort algorithm

Algorithm

1. Spilt a list in two parts - sorted and unsorted.


2. Iterate from arr[1] to arr[n] over the given array.
3. Compare the current element to the next element.
4. 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.

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 = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):

arr.append(int(input("Enter the element:")))


print ("The array is:",arr)
insertionSort(arr)
print("The sorted array is:",arr)
Output:

Enter the Size of the List:5


Enter the element:54
Enter the element:5
Enter the element:41
Enter the element:2
Enter the element:61
The array is: [54, 5, 41, 2, 61]
[5, 54, 41, 2, 61]
[5, 41, 54, 2, 61]
[2, 5, 41, 54, 61]
[2, 5, 41, 54, 61]
The sorted array is: [2, 5, 41, 54, 61]

Result:
Ex.No:7d Implementation of Quick Sort Algorithm
Date:
Aim:

To write a program to implement quick sort algorithm

Algorithm:

1. Select the Pivot Element as first, last, random and median element
2. Rearrange the Array
a. A pointer is fixed at the pivot element. The pivot element is compared with the
elements beginning from the first index.
b. If the element is greater than the pivot element, a second pointer is set for that
element.
c. 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.
d. Again, the process is repeated to set the next greater element as the second
pointer. And, swap it with another smaller element.
e. The process goes on until the second last element is reached.
f. Finally, the pivot element is swapped with the second pointer
3. Divide Subarrays
a. Pivot elements are again chosen for the left and the right sub-parts separately.
And, step 2 is repeated.
b. The subarrays are divided until each subarray is formed of a single element. At
this point, the array is sorted.
Program:

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)
quicksort(list1, first, p-1)
quicksort(list1, p+1, last)
list1 = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
list1.append(int(input("Enter the element:")))
print ("The array is:",list1)
quicksort(list1, 0, n-1)
print(list1)

Output:

Enter the Size of the List:5


Enter the element:45
Enter the element:6
Enter the element:25
Enter the element:64
Enter the element:2
The array is: [45, 6, 25, 64, 2]
The sorted array is: [2, 6, 25, 45, 64]

Result:
Ex.No:7e Implementation of Merge Sort Algorithm
Date:
Aim:
To write a program to implement Merge sort algorithm

Algorithm:

1. Create a merge sort function and declare list of values in array


2. Calculate the length for the given array
3. If the length is less than and equal one the list is already sorted, return the value.
4. Else, divide the list recursively into two halves: L and R, until it can no more be
divided.
5. Then, merge the smaller lists into new list in sorted order.
Program:

def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i=0
j=0
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):
arr[k] = R[j]
j += 1
k += 1
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
arr.append(int(input("Enter the element:")))
print ("The array is:",arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
Output:
Enter the Size of the List:7
Enter the element:54
Enter the element:5
Enter the element:41
Enter the element:12
Enter the element:17
Enter the element:65
Enter the element:7
The array is: [54, 5, 41, 12, 17, 65, 7]
Sorted array is:
5 7 12 17 41 54 65

Result
Ex.No:7f Implementation of Linear Search Algorithm
Date:
Aim:

To write a program to implement linear search algorithm

Algorithm:

1. Read the search element from the user


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

Program:

def linear_search(obj, item, start=0):


for i in range(start, len(obj)):
if obj[i] == item:
return i
return -1
arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
arr.append(int(input("Enter the element:")))
print ("The array is:",arr)
x=int(input("Enter the element to be search:"))
result=linear_search(arr,x)
if result==-1:
print ("element does not exist")
else:
print ("element exist in position %d" %result)

Output:
Enter the Size of the List:5
Enter the element:45
Enter the element:12
Enter the element:78
Enter the element:65
Enter the element:48
The array is: [45, 12, 78, 65, 48]
Enter the element to be search:12
element exist in position 1

Result:
Ex.No:7g Implementation of Binary Search Algorithm
Date:
Aim:

To write a program to implement binary search algorithm

Algorithm:

1. Given an input array that is supposed to be sorted in ascending order.


2. Take two variables which act as a pointer i.e, beg, and end.
3. Beg assigned with 0 and the end assigned to the last index of the array.
4. Now, introduce another variable mid which is the middle of the current array.
Then computed as (low+high)/2.
5. If the element present at the mid index is equal to the element to be searched,
then just return the mid index.
6. 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.
7. 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.

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 = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):

arr.append(int(input("Enter the element:")))

print ("The array is:",arr)

x=int(input("Enter the element to be search:"))

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")

Output:

Enter the Size of the List:4

Enter the element:1

Enter the element:2

Enter the element:3

Enter the element:4

The array is: [1, 2, 3, 4]

Enter the element to be search:3

Element is present at index 2

Result
Ex.No:8a Implementation of Hashing with linear probing
Date:
Aim:

To write a program to implement hash table using linear probing

Algorithm:

1. Initialize hash Table with all elements 0


2. Create a method that checks if the hash table is full or not
3. Create a method that returns position for a given element
4. Create a method that inserts element inside the hash table
a. checking if the table is full
b. checking if the position is empty
c. collision occurred , do linear probing
5. Create a method that searches for an element in the table
6. Returns position of element if found
7. Else returns False
a. If element is not found at position returned hash function
b. Then first we search element from position+1 to end
c. If not found then we search element from position-1 to 0
a. Check if the element is stored between position+1 to size
b. Now checking if the element is stored between position-1 to 0
8. Create a method to remove an element from the table
9. Create a method to display the hash table
a. Displaying the Table
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:

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

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

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(50)

table1.insert(100)

table1.insert(76)

table1.insert(85)

table1.insert(92)

table1.insert(73)

table1.insert(101)

table1.display()

print()

print("The position of element 92 is : " + str(table1.search(92)))

print("The position of element 85 is : " + str(table1.search(85)))

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

print()

table1.remove(73)

table1.display()
Output

Enter the Size of the hash table : 7

Element 50 at position 1

Element 100 at position 2

Element 76 at position 6

Collision has occured for element 85 at position 1 finding new Position.

Collision has occured for element 92 at position 1 finding new Position.

Collision has occured for element 73 at position 3 finding new Position.

Collision has occured for element 101 at position 3 finding new Position.

0 = 101

1 = 50

2 = 100

3 = 85

4 = 92

5 = 73

6 = 76

The number of element is the Table are : 7

The position of element 92 is : 4

The position of element 85 is : 3

Total number of comaprisons done for searching = 7

Element 73 is Deleted

0 = 101

1 = 50

2 = 100

3 = 85
4 = 92

5=0

6 = 76

The number of element is the Table are : 6

Result:
Ex.No:8b Implementation of Hashing with Quadratic Probing
Date:
Aim:

To write a program to implement Hashing with Quadratic Probing

Algorithm:

1. Initialize hash Table with all elements 0


2. Create a method that checks if the hash table is full or not
3. Create a method that returns position for a given element
4. Replace with hash function
5. Create a method to resolve collision by quadratic probing method
a. Start a loop to find the position and calculate new position by quadratic probing
b. If new position is empty then break out of loop and return new Position
c. Else, as the position is not empty increase i
6. Create a method that inserts element inside the hash table
a. Checking if the table is full
b. Checking if the position is empty, if empty position found , store the element
c. Collision occurred, do quadratic probing

7. Create a method that searches for an element in the table


8. Returns position of element if found
9. Else if element is not found at position returned hash function and then search element
using quadratic probing
a. Start a loop to find the position and calculate new position by quadratic probing
b. If element at new position is equal to the required element
c. Else, as the position is not empty increase i

10. Create a method to remove an element from the table


11. Create a method to display the hash table
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)

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)

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:

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]))

print("The number of element is the Table are : " + str(self.elementCount))

table1 = hashTable()

table1.insert(50)

table1.insert(100)

table1.insert(76)

table1.insert(85)

table1.insert(92)

table1.insert(73)

table1.insert(101)

table1.display()

print()

print("The position of element 92 is : " + str(table1.search(92)))

print("The position of element 85 is : " + str(table1.search(85)))

print("\nTotal number of comaprisons done for searching = " +

str(table1.comparisons))

print()

#table1.remove(90)

table1.remove(73)
table1.display()

Output:

Enter the Size of the hash table : 7

Element 50 at position 1

Element 100 at position 2

Element 76 at position 6
Collision has occured for element 85 at position 1 finding new Position.

Collision has occured for element 92 at position 1 finding new Position.

Collision has occured for element 73 at position 3 finding new Position.

Collision has occured for element 101 at position 3 finding new Position.

0 = 101

1 = 50

2 = 100

3 = 92

4 = 73

5 = 85

6 = 76

The number of element is the Table are : 7

The position of element 92 is : 3

The position of element 85 is : 5


Total number of comaprisons done for searching = 7

Element 73 is Deleted

0 = 101

1 = 50

2 = 100

3 = 92
4=0

5 = 85

6 = 76

The number of element is the Table are : 6

Result:
Ex.No:8c Implementation of Hashing with double hashing
Date:
Aim:

To write a program to implement Hashing with double hashing

Algorithm:

1. Initialize hash Table with all elements 0


2. Create a method that checks if the hash table is full or not
3. Create a method that returns position for a given element
4. Replace with hash function
5. Create another method that returns position for a given element
6. Create a method to resolve collision by double hashing method
a. Start a loop to find the position and calculate new position by double hashing
b. If new position is empty then break out of loop and return new Position
c. Else, as the position is not empty increase i
7. Create a method that inserts element inside the hash table
a. Checking if the table is full
b. Checking if the position is empty, if empty position found , store the
element
c. Collision occurred, do double hashing
8. Create a method that searches for an element in the table
9. Returns position of element if found
10. Else if element is not found at position returned hash function and then search element
using double hashing
a. Start a loop to find the position and calculate new position by double
hashing
b. If element at new position is equal to the required element
c. Else, as the position is not empty increase i
11. Create a method to remove an element from the table
12. Create a method to display the hash table

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

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:

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

found = True

break

elif self.table[position] == 0:

found = False

break

else:

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

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()
Output:

Enter the Size of the hash table : 10


Element 89 at position 9
Element 18 at position 8
Collision has occured for element 49 at position 9 finding new Position.
Collision has occured for element 58 at position 8 finding new Position.
Collision has occured for element 9 at position 9 finding new Position.

0=0
1=0
2=0
3 = 58
4=9
5=0
6 = 49
7=0
8 = 18
9 = 89
The number of element is the Table are : 5
The position of element 9 is : 4
The position of element 58 is : 3
Total number of comaprisons done for searching = 4
Element 18 is Deleted

0=0
1=0
2=0
3 = 58
4=9
5=0
6 = 49
7=0
8=0
9 = 89
The number of element is the Table are : 4

Result:
Ex.No:9 Implementation Of Tree Representation And Traversal Algorithm
Date:
Aim:

To write a program to implement tree representation and traversal algorithm

Algorithm:

1. Create a class and represent a node


2. Assign data to the new node, set left and right children to None
3. If tree is non empty, create a new node and compare to current node
4. If new node less than current node, then make it as left child of current node
5. If new node greater than current node, then make it as right child of current node
6. Else, if tree is empty ,add node to the root node
7. Create inorder method, then recursively traverse left,root, right order
8. Create preorder method, then recursively traverse root, left,right order
9. Create postorder method, then recursively traverse left,right,root order
10. Display all nodes
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()

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)


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))

Output

Inorder Traversal: [10, 14, 19, 27, 31, 35, 42]

Preorder Traversal: [27, 14, 10, 19, 35, 31, 42]

Postorder Traversal: [10, 19, 14, 31, 42, 35, 27]

Result
Ex.No:10a Implementation Of Binary Search Tree
Date:
Aim:

To write a program to implement binary search tree

Algorithm:
1. Insert node into the tree as the root of the tree.
2. Read the next element, if it is lesser than the root node element, insert it as the root of
the left sub-tree.
3. Otherwise, insert it as the root of the right of the right sub-tree
4. Compare the element with the root of the tree.
5. If the item is matched then return the location of the node.
6. Otherwise check if item is less than the element present on root, if so then move to
the left sub-tree.
7. If not, then move to the right sub-tree.
8. Repeat this procedure recursively until match found.
9. If element is not found then return NULL.
10. Find the data of the node to be deleted.
11. If the node is a leaf node, delete the node directly.
12. Else if the node has one child, copy the child to the node to be deleted and delete the
child node.
13. Else if the node has two children, find the inorder successor of the node.
14. Copy the contents of the inorder successor to the node to be deleted and delete the
inorder successor.

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):

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

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=' ')

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:
Ex.No:10b Implementation Of AVL Tree
Date:
Aim:

To write a program to implement AVL tree

Algorithm:

1. Create a class and represent a node


2. Assign data to the new node, set left and right children to None and set height is 1
3. If tree is non empty, create a new node and compare to current node
4. If new node less than current node, then make it as left child of current node
5. If new node greater than current node, then make it as right child of current node
6. Else, if tree is empty ,add node to the root node
7. After inserting the elements check the Balance Factor of each node.
8. If the balance factor of every node found like 0 or 1 or -1 then the algorithm perform
for the next operation.
9. 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.
10. Create a method to delete a node and find where the node is stored
11. If the node is a leaf node, delete the node directly.
12. Else if the node has one child, copy the child to the node to be deleted and delete the
child node.
13. Else if the node has two children, find the inorder successor of the node.
14. Copy the contents of the inorder successor to the node to be deleted and delete the
inorder successor.
15. Again do step 8 and 9
16. Display the preorder traversal

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),

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)

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)

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))

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 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:

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)

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
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

Result:
Ex.No:11a Implementation Of Max heap
Date:
Aim:

To write an program to implement max heap

Algorithm:

1. Use an array to store the data.


2. Start storing from index 1, not 0.
3. Create a insert method and find the size of the array
4. If the size is 0, then append the value
5. Else, append the value and set the range for heapify function
6. For any given node at position i:
7. If it is Left Child then l= [2*i+1]
8. If it is Right Child then r= [2*i+2]
9. Then find the maximum value and swap the position
10. Create delete method and delete the root node
11. Swap the position
12. Stop
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)
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)
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:
Ex.No:11b Implementation Of Min heap
Date:
Aim:

To write an program to implement min heap


Algorithm

1. Use an array to store the data.


2. Start storing from index 1, not 0.
3. Create a insert method and find the size of the array
4. If the size is 0, then append the value
5. Else, append the value and set the range for heapify function
6. For any given node at position i:
7. If it is Left Child then l= [2*i+1]
8. If it is Right Child then r= [2*i+2]
9. Then find the minimum value and swap the position
10. Create delete method and delete the root node
11. Swap the position
12. Stop
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) , print(A)

Output:

Min heap:
[1, 3, 2, 9, 4, 5]

Result:
Ex.No:12a Implementation Of Graph Representation Using Adjacency List
Date:
Aim:
To write a program to implement graph representation using Adjacency list
Algorithm:

1. Create an array of size and type of array must be list of vertices


2. Each array element is initialize with empty list
3. Create a add edge method to store v in list
4. Iterate each given edge of the form (u,v)
5. Append v to the uth list of array

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="")

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()
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

Result:
Ex.No:12b Implementation Of Graph Representation Using Adjacency Matrix
Date:
Aim:
To write a program to implement graph representation using Adjacency matrix
Algorithm:

1. Create a matrix of size N*N


2. Initialise it with zero
3. Iterate over each edge of the form(u,v)
4. Assign 1 to matix[u][v]
5. Checks if the vertex exists in the graph
6. Checks if the vertex is connecting to itself
7. Else, connecting the vertices
8. Define a remove function
9. Check the vertex is already present
10. Else, remove the vertex

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

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);

obj.displayAdjacencyMatrix();

#obj.addVertex();

#obj.addEdge(4, 1);

#obj.addEdge(4, 3);

obj.displayAdjacencyMatrix();

obj.removeVertex(1);

obj.displayAdjacencyMatrix();

Output

Adjacency Matrix:
0110
1010
1101
0010

Adjacency Matrix:
0110
1010
1101
0010

Adjacency Matrix:
010
101
010

Result:
Ex.No:12c Implementation Of Graph Traversal Algorithm Using BFS
Date:
Aim:
To write a program to implement graph traversal algorithm using BFS

Algorithm:
1. Start by putting any one of the graph's vertices at the back of a queue.
2. Take the front item of the queue and add it to the visited list.
3. 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.
4. Keep repeating steps 2 and 3 until the queue is empty.
Program
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
bfs_connected_component(graph,'A')
Output:
['A', 'B', 'C', 'E', 'D', 'F', 'G']

Result:
Ex.No:12d Implementation Of Graph Traversal Algorithm Using DFS
Date:
Aim:
To write a program to implement graph traversal algorithm using DFS
Algorithm:
1. Create a recursive function that takes the index of the node and a visited array.
2. Mark the current node as visited and print the node.
3. Traverse all the adjacent and unmarked nodes and call the recursive function with the
index of the adjacent node.
4. 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.
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(" ".join(path))
Output:

DFS
ABEICFJGDH

Result:
Ex.No:13 Implementation Of Single source shortest path algorithm
Date:
Aim:
To write a program to implement single source shortest path algorithm

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

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'))
Output:
shortest path
{'v1': 0, 'v2': 2, 'v3': 3, 'v4': 1, 'v5': 3, 'v6': 6, 'v7': 5}

Result:
Ex.No:14a Implementation Of Minimum spanning tree algorithm Using Kruskal’s
Date: algorithm

Aim:

To write a program to implement minimum spanning tree using Kruskal’s algorithm

Algorithm:
1. Sort all the edges in non-decreasing order of their weight.
2. Pick the smallest edge.
3. Check if it forms a cycle with the spanning tree formed so far.
4. If cycle is not formed, include this edge. Else, discard it.
5. 3. Repeat step2 until there are (V-1) edges in the spanning tree.
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) :
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)
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()
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
Ex.No:14b Implementation Of Minimum spanning tree algorithm Using Prim’s
Date: algorithm

Aim:

To write a program to implement minimum spanning tree using Prim’s algorithm

Algorithm:

1. Start at any node in the list


2. Choose a starting vertex is visited and assign all other vertices are unvisited
3. Find an edges e with minimum cost
4. Add the edge e found in previous to the spanning tree and change the edge as visited
5. Repeat the step 2 and 3 until all nodes become visited
6. Stop
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]):
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
Output:
Edge : Weight
0-3:1
0-1:2
3-2:2
3-6:4
6-5:1
6-4:6

Result:

You might also like