0% found this document useful (0 votes)
13 views13 pages

ADTs

The document contains code snippets and explanations of different data structures and algorithms including linear search, binary search, bubble sort, insertion sort, queues, stacks, and binary trees. Linear search and binary search are searching algorithms that search through an array. Bubble sort and insertion sort are sorting algorithms that sort arrays in ascending or descending order. Code examples are provided to demonstrate queue implementations like regular queues, priority queues, and circular queues using the queue module in Python. Stack implementations using lists are also demonstrated. Finally, a basic binary tree class is defined with nodes having left and right children.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views13 pages

ADTs

The document contains code snippets and explanations of different data structures and algorithms including linear search, binary search, bubble sort, insertion sort, queues, stacks, and binary trees. Linear search and binary search are searching algorithms that search through an array. Bubble sort and insertion sort are sorting algorithms that sort arrays in ascending or descending order. Code examples are provided to demonstrate queue implementations like regular queues, priority queues, and circular queues using the queue module in Python. Stack implementations using lists are also demonstrated. Finally, a basic binary tree class is defined with nodes having left and right children.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Linear Search (elements of array are already defined)

def LinearSearch(array, x):


for i in range(len(array)):
if x == array[i]:
print(x, "found at position", i+1)
return
print("Item does not exist")

array = [2002, 2025, 2023, 2005, 2001, 1998]


LinearSearch(array, 2002)

Binary Search
def binary_search(array, x):
min_value = 0
max_value = len(array) - 1
while min_value <= max_value:
mid = (min_value + max_value) // 2
if array[mid] == x:
print(x, "is present at position", str(mid))
return
elif array[mid] < x:
min_value = mid + 1
else:
max_value = mid - 1
print("Element is not found")

array = [1, 2, 3, 4, 5, 6, 7, 8]
print(array)
x = int(input("Enter the item to search from array = "))
binary_search(array, x)

Storing/ Swapping Values of Variables


x= 7
y = 9
temp = x
x = y
y = temp
print("Value of X is= ", x)
print("Value of Y is= ", y)
Bubble Sort
Ascending Order
def bubble_sort_descending(array):
n = len(array)
for i in range(n):
for j in range(0, n-i-1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array

array = [5, 2, 8, 1, 3]
sorted_array = bubble_sort_descending(array)
print(sorted_array)

Descending Order
def bubble_sort_descending(array):
n = len(array)
for i in range(n):
for j in range(0, n-i-1):
if array[j] < array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array
array = [5, 2, 8, 1, 3]
sorted_array = bubble_sort_descending(array)
print(sorted_array)

Pseudocode
DIM data() as INTEGER:{2,3,8,5,9,6,1,5,2}

DIM x,y,temp as INTEGER

For x = 0 to 8

For y= x+1 to 8

IF x < y THEN

Temp <— data(x)

Data(x) <—- data(y)

Data(y) <—— temp

End If

End For

End For
Bubble Sort taking inputs from use
Ascending Order
def bubble_sort(array):
n = len(array)
for i in range(n):
for j in range(0, n-i-1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array
array = []
for i in range(3):
num = int(input("Enter integer= "))
array.append(num)
bubble_sort(array)
print("Sorted Array:",array)

Descending Order
def bubble_sort(array):
n = len(array)
for i in range(n):
for j in range(0, n-i-1):
if array[j] < array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array
array = []
for i in range(3):
num = int(input("Enter integer= "))
array.append(num)
bubble_sort(array)
print("Sorted Array:",array)
Insertion Sort
Ascending Order
def insertion_sort(array):
for i in range(1, len(array)):
key = array [i]
j = i - 1
while j >= 0 and array [j] > key:
array [j + 1] = array [j]
j -= 1
array [j + 1] = key

array = [5, 2, 8, 1, 3]
insertion_sort(array)
print(array)

Descending Order
def insertion_sort_descending(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and array[j] < key: # here modified condition
array[j + 1] = array[j]
j -= 1
array[j + 1] = key

array = [5, 2, 8, 1, 3]
insertion_sort_descending(array)
print(array)

Insertion Sort Taking inputs from User (Ascending)


def insertion_sort(array):
for i in range(1, len(array)):
key = array [i]
j = i - 1
while j >= 0 and array [j] > key:
array [j + 1] = array [j]
j -= 1
array [j + 1] = key
array = []
for i in range(3):
num = int(input("Enter integer= "))
array.append(num)
insertion_sort(array)
print("Sorted Array:",array)
Insertion Sort Taking inputs from User (Descending)
def insertion_sort(array):
for i in range(1, len(array)):
key = array [i]
j = i - 1
while j >= 0 and array [j] < key:
array [j + 1] = array [j]
j -= 1
array [j + 1] = key
array = []
for i in range(3):
num = int(input("Enter integer= "))
array.append(num)
insertion_sort(array)
print("Sorted Array:",array)
Queues in Python
import queue
my_queue = queue.Queue()
my_queue.put((1, 'apple'))
my_queue.put((3, 'banana'))
my_queue.put((2, 'orange'))

print(my_queue.get()[1]) # prints 'apple'


print(my_queue.get()[1]) # prints 'orange'
print(my_queue.get()[1]) # prints 'banana

Queue
Python has built-in support for queues in the queue module. The queue module provides several classes for
implementing different types of queues, including:

1. Regular Queue
2. Priority Queue
3. Circular Queue
4. Dequeue Queue

Example of Regular Queue


import queue

# create a new queue


q = queue.Queue()

# add items to the queue


q.put(10)
q.put(20)
q.put(30)
print(q.queue)
# get items from the queue
print(q.get()) # prints 10
print(q.get()) # prints 20

# check the size of the queue


print(q.qsize()) # prints 1

#print whole queue


print(q.queue) #prints remaining/current items of the queue
Example of queue.LifoQueue: A last-in, first-out (LIFO) queue.
import queue

# create a new LIFO queue

q = queue.LifoQueue()

# add items to the queue

q.put(10)

q.put(20)

q.put(30)

print(q.queue) #prints all elements of queue

print(q.get()) # prints 30

print(q.get()) # prints 20

print(q.qsize()) # prints 1

Example of queue.PriorityQueue : A queue where items are dequeued in order of priority.


import queue

# create a new priority queue

q = queue.PriorityQueue()

# add items to the queue

q.put((2, 'item 1'))

q.put((1, 'item 2'))

q.put((3, 'item 3'))

print(q.queue)

# get items from the queue

print(q.get()) # prints (1, 'item 2')

print(q.get()) # prints (2, 'item 1')

# check the size of the queue

print(q.qsize()) # prints 1
Example of Circular Queue
## 1. Defining Class
class CircularQueue:
def __init__(self, max_size):
self.max_size = max_size
self.queue = [None] * max_size
self.front = self.rear = -1

## 2. Defining Empty Function

def is_empty(self):
return self.front == -1

## 3. Defining Full Function

def is_full(self):
return (self.rear + 1) % self.max_size == self.front

## 4. Defining Enqueue Function

def enqueue(self, item):


if self.is_full():
print("Queue is full")
elif self.is_empty():
self.front = self.rear = 0
self.queue[self.rear] = item
else:
self.rear = (self.rear + 1) % self.max_size
self.queue[self.rear] = item

## 5. Defining Dequeue Function

def dequeue(self):
if self.is_empty():
print("Queue is empty")
elif self.front == self.rear:
item = self.queue[self.front]
self.front = self.rear = -1
return item
else:
item = self.queue[self.front]
self.front = (self.front + 1) % self.max_size
return item
## 6. Defining Display Function

def display(self):
if self.is_empty():
print("Queue is empty")
elif self.rear >= self.front:
for i in range(self.front, self.rear + 1):
print(self.queue[i], end=" ")
print()
else:
for i in range(self.front, self.max_size):
print(self.queue[i], end=" ")
for i in range(0, self.rear + 1):
print(self.queue[i], end=" ")
print()

# Create a circular queue with a max size of 5


cq = CircularQueue(5)

# Enqueue elements
cq.enqueue(1)
cq.enqueue(2)
cq.enqueue(3)
cq.enqueue(4)
cq.enqueue(5)

# Display the circular queue


cq.display() # Output: 1 2 3 4 5

# Dequeue elements
print("Dequeue:", cq.dequeue()) # Output: Dequeue: 1
print("Dequeue:", cq.dequeue()) # Output: Dequeue: 2

# Display the circular queue after dequeues


cq.display() # Output: 3 4 5

Stack

In Python, a stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle, which means
that the last element added to the stack will be the first one to be removed. The basic operations that can be
performed on a stack are push, pop, and peek. Here's an example implementation of a stack in Python:

# create an empty stack


stack = []
# add elements to the stack
stack.append('apple')
stack.append('banana')
stack.append('orange')
# print the stack
print(stack) # output: ['apple', 'banana', 'orange']

# remove the last element from the stack


stack.pop()

# print the stack again


print(stack) # output: ['apple', 'banana']

In the above example above, we first create an empty stack using a list. We then add three elements ('apple',
'banana', 'orange') to the stack using the append() method, which adds the elements to the end of the list.
We can remove an element from the stack using the pop() method, which removes and returns the last
element from the list. In the example above, we remove the last element ('orange') from the stack using
pop(), and print the updated stack.

Note that we can also access the last element of the stack without removing it using the indexing notation
stack[-1].

_______________________________________________________________________________________
# Create an empty stack
stack = []

# Push (Add) items to the stack using the append() method


stack.append(1)
stack.append(2)
stack.append(3)

# Check the current state of the stack


print(stack) # Output: [1, 2, 3]

# Pop(Remove) the top item from the stack using the pop() method
top_item = stack.pop()
print(top_item) # Output: 3

# Check the current state of the stack again


print(stack) # Output: [1, 2]
Binary Tree
class BinaryTree:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None

def insert_left(self, value):


if self.left_child is None:
self.left_child = BinaryTree(value)
else:
new_node = BinaryTree(value)
new_node.left_child = self.left_child
self.left_child = new_node

def insert_right(self, value):


if self.right_child is None:
self.right_child = BinaryTree(value)
else:
new_node = BinaryTree(value)
new_node.right_child = self.right_child
self.right_child = new_node

In this implementation, we define a BinaryTree class that has a constructor that takes a value as input and
initializes the node with that value, as well as left_child and right_child attributes that are initially set to
None. The BinaryTree class also has two methods, insert_left and insert_right, that allow us to add
child nodes to the left or right of the current node.

To use this binary tree, we can create a root node and then add child nodes as desired using the insert_left
and insert_right methods. For example:

# create a root node with value 1


root = BinaryTree(1)

# add a left child with value 2


root.insert_left(2)

# add a right child with value 3


root.insert_right(3)

# add a left child to the left child with value 4


root.left_child.insert_left(4)

# add a right child to the left child with value 5


root.left_child.insert_right(5)
Link List
A linked list is a data structure that consists of a sequence of elements, where each element contains a value
and a reference (or pointer) to the next element in the sequence. In Python, we can implement a linked list
using classes and objects. Here's an example of creating and manipulating a linked list in Python:

StartPointer = 0

EmptyList = 5

#create a class with the name of node


class node:
def __init__(self, theData, nextNodeNumber):
self.data = theData
self.nextNode = nextNodeNumber
linkedList = [node(1,1),node(5,4),node(6,7),node(7,-1),node(2,2),node(-1,6),
node(-1,7),node(56,3),node(-1,9),node(-1,-1)]
startPointer = 0
emptyList = 5

#create output node to get output from linked list


def outputNodes(linkedList,startPointer):
while (startPointer != -1):
print(str(linkedList[startPointer].data))
startPointer = linkedList[startPointer].nextNode
#Add new nodes in linked list
def addNode(linkedList, startPointer, emptyList):
dataToAdd = input("Enter the data to add= ") #takes input from user to add in
linked list
if emptyList <0 or emptyList > 9:
return False
else:
newNode = node(int(dataToAdd), -1)
linkedList[emptyList] = (newNode)
nextPointer = 0
while(startPointer != -1):
nextPointer = startPointer
startPointer = linkedList[startPointer].nextNode
linkedList[nextPointer].nextNode = emptyList
return True
print("Current Linked List is given below;")
outputNodes(linkedList, startPointer)

#Call output of link list to show updated linked list


returnValue = addNode(linkedList, startPointer, emptyList)
if returnValue == True:
print("Item successfully added")
else:
print("Item not added, list full")

print("New updated linked list is;")


outputNodes(linkedList, startPointer)

You might also like