I B.Sc.,Python Lab (2023-2024)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

ARIGNAR ANNA GOVERNMENT ARTS COLLEGE

(Accredited with “C” Grade by NAAC & Affiliated to the Periyar University)
Vadachennimalai (Po), Attur (T.K),
Salem (D.T) - 636121
Ph.No.04282-235001, www.aagacattur.org.in

I - B.Sc., COMPUTER SCIENCE PRACTICAL


RECORD

DATA STRUCTURE AND ALGORITHMS LAB

DEPARTMENT OF COMPUTER SCIENCE


(2023-2024)
ARIGNAR ANNA GOVERNMENT ARTS COLLEGE
(Accredited with “C” Grade by NAAC & Affiliated to the Periyar University)
Vadachennimalai (Po), Attur (T.K),
Salem (D.T)-636121
Ph.No.04282-235001, www.aagacattur.org.in

RECORD OF PRACTICAL WORK IN COMPUTER SCIENCE

NAME
CLASS
SUBJECT

UNIVERSITY REGISTER No.

Certified that this a bonafide record of the work done in Arignar Anna Govt. Arts college, in the
Computer Laboratory during the academic year 2023-2024.
Submitted for the University Practical Examination held on

Lecturer-in-charge Head of the Department


Station:

Date : Internal/External Examiner

1.

2.
INDEX
PAGE
EX.
DATE CONTENT NO SIGN
NO

1 IMPLEMENT THE SIMPLE ADTS AS


PYTHON CLASSES

2
STACK AND QUEUE ADT

3
IMPLEMENT THE LIST ADT

4
IMPLEMENT PRIORITY QUEUE ADT

5 INSERT, DELETE AND SEARCH ELEMENT


FROM A BINARY TREE

6 INSERTION AND DELETION FROM AN


AVL-TREE

7 IMPLEMENTATION OF BFS AND DFS FOR


A GIVEN GRAPH

8
META AND BINARY SEARCH

9 BUBBLE , SELECTION AND INSERTION


SORT
/* PROGRAM TO IMPLEMENT THE SIMPLE ADTS AS PYTHON CLASSES */

AIM:
To write a Python program that appends, deletes and displays elements of a list using classes.

ALGORITHM:

Step 1: Create a class and using a constructor initialize values of that class.

Step 2: Create methods for adding, removing and displaying elements of the list and return the respective
values.

Step 3: Create an object for the class.

Step 4: Using the object, call the respective function depending on the choice taken from the user.

Step 5: Print the final list.

Step 6: Exit
PROGRAM:
class SimpleListADT:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def add(self, item):
self.items.append(item)
def remove(self, item):
if item in self.items:
self.items.remove(item)
else:
print(f"{item} not found in the list.")
# Example usage:
my_list = SimpleListADT()
print("Is the list empty?", my_list.is_empty())
print("Size of the list:", my_list.size())
my_list.add(1)
my_list.add(2)
my_list.add(3)
print("Is the list empty?", my_list.is_empty())
print("Size of the list:", my_list.size())
print("List items:", my_list.items)
my_list.remove(2)
print("Size of the list after removing 2:", my_list.size())
print("List items after removal:", my_list.items)
OUTPUT:
Is the list empty? True
Size of the list: 0
Is the list empty? False
Size of the list: 3
List items: [1, 2, 3]
Size of the list after removing 2: 2
List items after removal: [1, 3]

RESULT:
Thus, the Python program that appends, deletes and displays elements of a list using classes has
been implemented successfully.
/* PROGRAMS TO IMPLEMENT THE FOLLOWING USING A SINGLY
LINKED LIST */

A. IMPLEMENTATION OF STACK

AIM:
To write a python program creates a stack and allows the user to perform push
and pop operations on it.

ALGORITHM:
Step 1: Create a class Node with instance variables data and next.

Step 2: Create a class Stack with instance variable head.

Step 3: The variable head points to the first element in the linked list.

Step 4: Define methods push and pop inside the class Stack.

Step 5: The method push adds a node at the front of the linked list.

Step 6: The method pop returns the data of the node at the front of the linked list and
removes the node. It returns None if there are no nodes.

Step 7: Create an instance of Stack and present a menu to the user to perform operations
on the stack.
PROGRAM:
class Stack_struct:
def __init__(self):
self.items = []
def check_empty(self):
return self.items == []
def add_elements(self, my_data):
self.items.append(my_data)
def delete_elements(self):
return self.items.pop()
my_instance = Stack_struct()
while True:
print('Push <value>')
print('Pop')
print('Quit')
my_input = input('What operation would you like to perform ? ').split()
my_op = my_input[0].strip().lower()
if my_op == 'push':
my_instance.add_elements(int(my_input[1]))
elif my_op == 'pop':
if my_instance.check_empty():
print('The stack is empty')
else:
print('The deleted value is : ', my_instance.delete_elements())
elif my_op == 'Quit':
break
OUTPUT
Push <value>
Pop
Quit
What operation would you like to perform? Push 6
Push <value>
Pop
Quit
What operation would you like to perform? Push 8
Push <value>
Pop
Quit
What operation would you like to perform? Push 34
Push <value>
Pop
Quit
What operation would you like to perform? Pop
The deleted value is : 6
Push <value>
Pop
Quit

RESULT:
Thus the python program to creates a stack and allows the user to perform push and pop
operations on it has been executes successfully
B. IMPLEMENTATION OF QUEUE

AIM:
To write a python program creates a queue and allows the user to perform enqueue and
dequeueoperations on it.

ALGORITHM:
Step 1: Create a class Node with instance variables data and next.

Step 2: Create a class Queue with instance variables head and last.

Step 3: The variable head points to the first element in the linked list while last points to
the last element.

Step 4: Define methods enqueue and dequeue inside the class Queue.

Step 5: The method enqueue adds a node at the end of the linked list.

Step 6: The method dequeue returns the data of the node at the front of the linked list and
removes the node. It returns None if there are no nodes.

Step 7: Create an instance of Queue and present a menu to the user to perform operations
on thequeue.
PROGRAM:
class Queue_struct:
def __init__(self):
self.items = []
def check_empty(self):
return self.items == []
def enqueue_elem(self, data):
self.items.append(data)
def dequeue_elem(self):
return self.items.pop(0)
my_instance = Queue_struct()
while True:
print('Enqueue <value>')
print('Dequeue')
print('Quit')
my_input = input('What operation would you perform ? ').split()
operation = my_input[0].strip().lower()
if operation == 'Enqueue':
my_instance.enqueue_elem(int(my_input[1]))
elif operation == 'Dequeue':
if my_instance.check_empty():
print('The queue is empty...')
else:
print('The deleted value is : ', my_instance.dequeue_elem())
elif operation == 'Quit':
break
OUTPUT
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Enqueue 45
Enqueue <value>
Dequeue
Quit
What operation would you perform? Enqueue 56
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Enqueue 89
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Dequeue
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Dequeue
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Quit

RESULT:
Thus, the python program to creates a queue and allows the user to perform enqueue and
dequeue operations on it has been executes successfully.
/*PROGRAM TO IMPLEMENT THE LIST ADT USING PYTHON ARRAYS*/

AIM:
To write a Python program to implement list using Array and linked list.

ALGORITHM:
Step 1: Start.

Step 2: Declare the necessary functions for implementation. Get the input from the user
and store it an array and linked list.

Step 3: In Insertion, half of the elements to be shifted upwards and in deletion half of the
elements to be shifted downwards.

Step 4: Display the output using an array.

Step 5: Stop.
PROGRAM:
//Accessing Array Element
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
//Insertion Operation
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
from array import *
array1 = array('i', [10,20,30,40,50])
array1.insert(1,60)
for x in array1:
print(x)
//Deletion Operation
from array import *
array1 = array('i', [10,20,30,40,50])
array1.remove(40)
for x in array1:
print(x)
// Search Operation
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1.index(40))
//Update Operation
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)
OUTPUT

RESULT:
Thus, the Python program for creation and insertion to implement list using an array has
been executed successfully.
/* PROGRAM TO IMPLEMENT PRIORITY QUEUE ADT* /

AIM:
To write a Python program to implement priority Queue ADT.

ALGORITHM:
Step 1: Start the Program.

Step 2: The Node class will be the element inserted in the priority queue.

Step 3: To add a new data element (Node) in the priority queue.If the priority queue is

empty, we will insert the element to it.

Step 4: When we remove a data from a priority queue(min), the data at the top, which

will be the data with least priority, will get removed.

Step 5: Display the output using an Priority Queue.

Step 6: Stop the Program..


PROGRAM:
class PriorityQueue(object):
def __init__(self):
self.queue = []
def __str__(self):
return ' '.join([str(i) for i in self.queue]
# check if the queue is empty
def isEmpty(self):
return len(self.queue) == 0
# inserting an element in the queue
def insert(self, data):
self.queue.append(data)
# popping an element based on Priority
def delete(self):
try:
max_val = 0
for i in range(len(self.queue)):
if self.queue[i] > self.queue[max_val]:
max_val = i
item = self.queue[max_val]
del self.queue[max_val]
return item
except IndexError:
print()
exit()
if __name__ == '__main__':
pQueue = PriorityQueue()
print("Priority Queue: ")
pQueue.insert(45)
pQueue.insert(29)
pQueue.insert(19)
pQueue.insert(97)
print(pQueue)
while not pQueue.isEmpty(): print(pQueue.delete())
OUTPUT
Priority Queue:
45 29 19 97
97
45
29
19

RESULT:
Thus, the python program to creates a queue and allows the user to perform Priority
Queue operations on it has been executes successfully.
/*PROGRAM TO PERFORM THE INSERT, DELETE AND SEARCH KEY
ELEMENT */

AIM:
To write a python program creates a binary search tree and presents a
menu to the user to perform insertion, deletion and inorder traversal
operations.

ALGORITHM:
Step 1:Start the Program
Step 2: Given a BST, the task is to insert a new node in this BST.
Step 3: Check the value to be inserted (say X) with the value of the current node
(say val)
Step 4: Once the leaf node is reached, insert X to its right or left based on the relation
between X and the leaf node’s value.
Step 5: Display the result using insert an Binary Search Tree.
Step 6: Stop the Program.
PROGRAM:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val == key:
return root
elif root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)
if __name__ == '__main__':
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
inorder(r)
OUTPUT:
> 10
20 30 40 50 60 70 80 10

RESULT:
Thus, the python program to implement the concept of binary search tree. has been
implemented successfully.
/* B. DELETE AN ELEMENT FROM A BINARY SEARCH TREE */

AIM:
To write a python program creates a binary search tree and presents a
menu to the user to perform insertion, deletion and inorder traversal
operations.

ALGORITHM:
Step 1: Start the Program.

Step 2: The method replace_node_of_parent takes a node as argument and replaces the
current object in the BST with the node.

Step 3: The method find_min finds the the left-most node in the BST with the BSTNode
object as root.

Step 4: The method remove removes the current BSTNode object from the BST.

Step 5: Display the result using Binary Search Tree.

Step 6: Stop the program.


PROGRAM:
class Tree:
def __init__(node, value):
node.value = value
node.left = None
node.right = None
def Inorder( node, Root ):
if( Root is None ):
return
node.Inorder(Root.left)
print(Root.value,end = ' ')
node.Inorder(Root.right)
def Insert(node, value):
if node is None:
node = Tree(value)
elif value < node.value:
if node.left is None:
node.left = Tree(value)
else:
node.left.Insert(value)
else:
if node.right is None:
node.right = Tree(value)
else:
node.right.Insert(value)
def Delete(node,temp, value):
if value < node.value:
temp = node
node.left.Delete(temp,value)
elif(value > node.value):
temp = node
node.right.Delete(temp, value)
else:
if (node.left is None and node.right is None):
if(temp.left == node):
temp.left = None
else:
temp.right = None
node = None
elif node.right is None :
if(temp.left == node):
temp.left = node.left
else:
temp.right = node.left
node = None
elif node.left is None :
if(temp.left == node):
temp.left = node.right
else:
temp.right = node.right
node = None
else:
temp = node.right
while(temp.left is not None):
temp = temp.left
node.value = temp.value
node.right.Delete(temp,temp.value)
Root = Tree(6)
Root.Insert(4)
Root.Insert(2)
Root.Insert(5)
Root.Insert(9)
Root.Insert(8)
Root.Insert( 10)
print ("Inorder traversal after insertion: ",end = '')
Root.Inorder(Root)
Root.Delete(Root, 2)
print ('\n 2 is deleted: ',end ='')
Root.Inorder(Root)
Root.Delete(Root, 4)
print ('\n 4 is deleted: ',end ='')
Root.Inorder(Root)
Root.Delete(Root, 6)
print ('\n 6 is deleted: ',end ='')
Root.Inorder(Root)

OUTPUT:
Inorder traversal after insertion: 2 4 5 6 8 9 10
2 is deleted: 4 5 6 8 9 10
4 is deleted: 5 6 8 9 10
6 is deleted: 5 8 9 10

RESULT:
Thus, the python program to implement the concept of binary search tree. has been
implemented successfully.
/* C. SEARCH FOR A KEY ELEMENT IN A BINARY SEARCH TREE */

AIM:
To write a python program creates a binary search tree and presents a menu to the user to
perform insertion, deletion and inorder traversal operations.

ALGORITHM:
Step 1: Start the Program.
Step 2: The method search takes a key as argument and returns the node with that key in
the BST withthe BSTNode object as root.
Step 3: Create a class BSTree with instance variable root.
Step 4: Define methods inorder, add, remove and search in BSTree.
Step 5: The method inorder calls the inorder method of the root node.\
Step 6: Display the result using Binary Search Tree.
Step 7: Stop the program.
PROGRAM:
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def search(root, key):
if root is None or root.key == key:
return root
if root.key < key:
return search(root.right, key)
return search(root.left, key)
if __name__ == '__main__':
root = None
root = insert(root, 50)
insert(root, 30)
insert(root, 20)
insert(root, 40)
insert(root, 70)
insert(root, 60)
insert(root, 80)
key = 6
if search(root, key) is None:
print(key, "not found")
else:
print(key, "found")
key = 60
if search(root, key) is None:
print(key, "not found")
else:
print(key, "found")
OUTPUT
6 not found
60 found

RESULT:
Thus, the python program to implement the concept of binary search tree. has been
implemented successfully.
/* PROGRAM TO PERFORM THE INSERTION AND DELETION FROM AN
AVL-TREE */

AIM:
To write a python program creates a AVL tree and presents a menu to the user to
perform insertion, operations.

ALGORITHM:
Step 1: Start the Program.
Step 2 - Insert the new element into the tree using Binary Search Tree insertion logic.

Step 3 - After insertion, check the Balance Factor of every node.

Step 4 - If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.

Step 5 - If the Balance Factor of any node is other than 0 or 1 or -1 then that tree is

said to be imbalanced. In this case, perform suitable Rotation to make it balanced and go

for next operation.

Step 6: Display the result using AVL Tree.

Step 7: Stop the program.


PROGRAM:
class Node:
def __init__(self, key):
self.key = key
self.height = 1
self.left = None
self.right = None
def height(node):
if node is None:
return 0
return node.height
def update_height(node):
if node is not None:
node.height = 1 + max(height(node.left), height(node.right))
def balance_factor(node):
if node is None:
return 0
return height(node.left) - height(node.right)
def left_rotate(y):
x = y.right
T2 = x.left
x.left = y
y.right = T2
update_height(y)
update_height(x)
return x
def right_rotate(x):
y = x.left
T2 = y.right
y.right = x
x.left = T2
update_height(x)
update_height(y)
return y
def insert(root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
update_height(root)
balance = balance_factor(root)
if balance > 1:
if key < root.left.key:
return right_rotate(root)
else:
root.left = left_rotate(root.left)
return right_rotate(root)
if balance < -1:
if key > root.right.key:
return left_rotate(root)
else:
root.right = right_rotate(root.right)
return left_rotate(root)
return root
def pre_order_traversal(root):
if root:
print(root.key, end=" ")
pre_order_traversal(root.left)
pre_order_traversal(root.right)
root = None
keys = [10, 20, 30, 40, 50, 25]
for key in keys:
root = insert(root, key)
print("Pre-order traversal of AVL tree:")
pre_order_traversal(root)
OUTPUT
Pre-order traversal of AVL tree:
> 60
30 20 10 25 40 50 60

RESULT:
Thus, the python program to implement the concept of insertion an AVL tree. has been
implemented successfully.
/*B. DELETION FROM AN AVL-TREE */

AIM:
To write a python program creates a AVL tree and presents a menu to the user to
perform deletion, operations.

ALGORITHM:
Step 1: Start the Program.
Step 2 - Delete the element into the tree using Binary Search Tree deletion logic.
Step 3 - After deletion, check the Balance Factor of every node.
Step 4 - If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
Step 6: Display the result using AVL Tree.
Step 7: Stop the program.
PROGRAM
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.height = 1
class AVLTree(object):
def insert(self, root, key):
if not root:
return Node(key)
elif key < root.data:
root.left = self.insert(root.left, key)
else:
root.right = self.insert(root.right, key)
root.h = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
b = self.getBalance(root)
if b > 1 and key < root.left.data:
return self.rightRotate(root)
if b < -1 and key > root.right.data:
return self.leftRotate(root)
if b > 1 and key > root.left.data:
root.left = self.lefttRotate(root.left)
return self.rightRotate(root)
if b < -1 and key < root.right.data:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
def delete(self, root, key):
if not root:
return root
elif key < root.data:
root.left = self.delete(root.left, key)
elif key > root.data:
root.right = self.delete(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.getMindataueNode(root.right)
root.data = temp.data
root.right = self.delete(root.right, temp.data)
if root is None:
return root
root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right))
balance = self.getBalance(root)
if balance > 1 and self.getBalance(root.left) >= 0:
return self.rightRotate(root)
if balance < -1 and self.getBalance(root.right) <= 0:
return self.leftRotate(root)
if balance > 1 and self.getBalance(root.left) < 0:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
if balance < -1 and self.getBalance(root.right) > 0:
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))
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 Inorder(self, root):
if root.left:
self.Inorder(root.left)
print(root.data, end = " ")
if root.right:
self.Inorder(root.right)
Tree = AVLTree()
root = None
root = Tree.insert(root, 10)
root = Tree.insert(root, 13)
root = Tree.insert(root, 11)
root = Tree.insert(root, 14)
root = Tree.insert(root, 12)
root = Tree.insert(root, 15)
# Inorder Traversal
print("AVL Tree: ")
Tree.Inorder(root)
root = Tree.delete(root, 14)
print("\nAfter deletion: ")
Tree.Inorder(root)
OUTPUT:
AVL Tree:
10 11 12 13 14 15
After deletion:
10 11 12 13 15

RESULT:
Thus, the python program to implement the concept of insertion an AVL tree. has been
implemented successfully.
/*PROGRAMS FOR THE IMPLEMENTATION OF BFS AND DFS FOR A
GIVEN GRAPH*/

AIM:
To write a Python program to implementation of BFS and DFS for a given graph.

ALGORITHM:
Step 1: Start the program.

Step 2: The BFS and DFS algorithm will traverse all the nodes in the graph starting from

the root and keep them dropping after they are completed or visited:-

Step 3: BFS and DFS visits an adjacent unvisited node, marks it as done, and inserts it

into a queue.

Step 4: Remove the previous vertex from the queue if in case there is no adjacent vertex.

Step 5: BFS and DFS algorithm will iterate until all the vertices are traversed.

Step 6: Display the result using BFS and DFS

Step 7: Stop the Program.


PROGRAM:
//BREADTH FIRST SEARCH
graph = {
'A': ['B', 'C', "D"],
'B': ['E', "F"],
'C': ['G', "I"],
'D': ["I"],
'E': [],
"F": [],
'G': [],
"I": []
}
def bfs(visit_complete, graph, current_node):
visit_complete.append(current_node)
queue = []
queue.append(current_node)
while queue:
s = queue.pop(0)
print(s)
for neighbour in graph[s]:
if neighbour not in visit_complete:
visit_complete.append(neighbour)
queue.append(neighbour)
bfs([], graph, 'A')

//DEPTH FIRST SEARCH


graph1 = {
'A' : ['B','S'],
'B' : ['A'],
'C' : ['D','E','F','S'],
'D' : ['C'],
'E' : ['C','H'],
'F' : ['C','G'],
'G' : ['F','S'],
'H' : ['E','G'],
'S' : ['A','C','G']
}

def dfs(graph, node, visited):


if node not in visited:
visited.append(node)
for k in graph[node]:
dfs(graph,k, visited)
return visited

visited = dfs(graph1,'A', [])


print(visited)
OUTPUT
['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']

RESULT
Thus, the python program to implement the BFS and DFS for a given graph . has been
implemented successfully.
/*PROGRAMS FOR IMPLEMENTING THE META SEARCH AND BINARY
SEARCH*/

AIM:
To write a Python program to implementation of meta search and binary search
for a searching methods.

ALGORITHM:
Step 1: Start the Program.

Step 2: Compare the middle element of the search space with the key.

Step 3: If the key is found at middle element, the process is terminated.

Step 4: If the key is not found at middle element, choose which half will be used as the

next search space.

Step 5: Display the result using meta and binary Search.

Step 6: Stop the Program.


PROGRAM:
META SEARCH
import math
def bsearch(A, key_to_search):
n = len(A)
# Set number of bits to represent
lg = int(math.log2(n-1)) + 1;
# largest array index
#while ((1 << lg) < n - 1):
#lg += 1
pos = 0
for i in range(lg - 1, -1, -1) :
if (A[pos] == key_to_search):
return pos
# Incrementally construct the
# index of the target value
new_pos = pos | (1 << i)
# find the element in one
# direction and update position
if ((new_pos < n) and
(A[new_pos] <= key_to_search)):
pos = new_pos
# if element found return
# pos otherwise -1
return (pos if(A[pos] == key_to_search) else -1)
# Driver code
if __name__ == "__main__":
A = [ -2, 10, 100, 250, 32315 ]
print( bsearch(A, 10))

OUTPUT
1
//BINARY SEARCH
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l) // 2
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element
# was not present
return -1
# Driver Code
if __name__ == '__main__':
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", result)
else:
print("Element is not present in array")
OUTPUT
Element is present at index 3

RESULT
Thus, the python program to implement the Meta and binary search for a sorting methods
has been implemented successfully.
/*PROGRAMS FOR IMPLEMENTING BUBBLE, SELECTION AND
INSERTION SORTING METHODS*/

AIM:
To Perform the Bubble. Selection and Insertion Sorting in Python Programming.

ALGORITHM:
Step 1: Start

Step 2: Define list of elements(alist)

Step 3: Take first element find its appropriate position and insert them

Step 4: Repeat till every element is sorted

Step 5: Print the list of elements

Step 6: Stop
PROGRAM:
// BUBBLE SORTING
def bubblesort(list):
# Swap the elements to arrange in order
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
list = [19,2,31,45,6,11,121,27]
bubblesort(list)
print(list)

OUTPUT
[2, 6, 11, 19, 27, 31, 45, 121]

//SELECTION SORTING
def selection_sort(input_list):
for idx in range(len(input_list)):
min_idx = idx
for j in range( idx +1, len(input_list)):
if input_list[min_idx] > input_list[j]:
min_idx = j
# Swap the minimum value with the compared value
input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]
l = [19,2,31,45,30,11,121,27]
selection_sort(l)
print(l)

OUTPUT
[2, 11, 19, 27, 30, 31, 45, 121]
//INSERTION SORTING
def insertion_sort(InputList):
for i in range(1, len(InputList)):
j = i-1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j+1] = InputList[j]
j=j-1
InputList[j+1] = nxt_element
list = [19,2,31,45,30,11,121,27]
insertion_sort(list)
print(list)

OUTPUT
[19, 2, 31, 45, 30, 11, 27, 121]

RESULT:
Thus, the python program to perform Bubble, Insertion, and Selection Sort is created and
executed successfully.

You might also like