I'm unable to create a .docx file directly, but I can provide the code for each of the tasks you've listed. You can copy and paste the code into a Word document as needed. Below are the implementations for each task without any explanations or comments.
1. Binary Search Tree Operations
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 key < root.val:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
def longest_path(root):
if root is None:
return 0
left = longest_path(root.left)
right = longest_path(root.right)
return max(left, right) + 1
def find_min(root):
current = root
while current.left is not None:
current = current.left
return current.val
def swap_children(root):
if root is None:
return
root.left, root.right = root.right, root.left
swap_children(root.left)
swap_children(root.right)
def search(root, key):
if root is None or root.val == key:
return root
if key < root.val:
return search(root.left, key)
return search(root.right, key)
# Example usage
values = [50, 30, 70, 20, 40, 60, 80]
root = None
for val in values:
root = insert(root, val)
# Insert new node
root = insert(root, 25)
# Number of nodes in longest path
longest = longest_path(root)
# Minimum data value
minimum = find_min(root)
# Swap children
swap_children(root)
# Search a value
found = search(root, 40)
2. Optimal Binary Search Tree
def optimal_bst(keys, freq, n):
cost = [[0 for x in range(n)] for y in range(n)]
for i in range(n):
cost[i][i] = freq[i]
for L in range(2, n+1):
for i in range(n-L+1):
j = i + L -1
cost[i][j] = float('inf')
for r in range(i, j+1):
c = 0
if r > i:
c += cost[i][r-1]
if r < j:
c += cost[r+1][j]
c += sum(freq[i:j+1])
if c < cost[i][j]:
cost[i][j] = c
return cost[0][n-1]
keys = [10, 12, 20]
freq = [34, 8, 50]
n = len(keys)
optimal_cost = optimal_bst(keys, freq, n)
3. Linear Search and Binary Search with Complexity Analysis
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
def binary_search(arr, x):
left = 0
right = len(arr) -1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
left = mid +1
else:
right = mid -1
return -1
# Example usage
arr = [2, 3, 4, 10, 40]
x = 10
lin_result = linear_search(arr, x)
bin_result = binary_search(arr, x)
4. Quick Sort in Ascending and Descending Order
def quick_sort(arr, low, high, ascending=True):
if low < high:
pi = partition(arr, low, high, ascending)
quick_sort(arr, low, pi-1, ascending)
quick_sort(arr, pi+1, high, ascending)
def partition(arr, low, high, ascending):
pivot = arr[high]
i = low -1
for j in range(low, high):
if ascending:
if arr[j] < pivot:
i +=1
arr[i], arr[j] = arr[j], arr[i]
else:
if arr[j] > pivot:
i +=1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
# Example usage
arr = [10, 7, 8, 9, 1, 5]
quick_sort(arr, 0, len(arr)-1, ascending=True) # Ascending
quick_sort(arr, 0, len(arr)-1, ascending=False) # Descending
5. Quick Sort with Different Pivot Selection
import random
def quick_sort_pivot(arr, low, high, pivot_type='first'):
if low < high:
pi = partition_pivot(arr, low, high, pivot_type)
quick_sort_pivot(arr, low, pi-1, pivot_type)
quick_sort_pivot(arr, pi+1, high, pivot_type)
def partition_pivot(arr, low, high, pivot_type):
if pivot_type == 'first':
arr[high], arr[low] = arr[low], arr[high]
elif pivot_type == 'random':
rand_pivot = random.randint(low, high)
arr[high], arr[rand_pivot] = arr[rand_pivot], arr[high]
pivot = arr[high]
i = low -1
for j in range(low, high):
if arr[j] < pivot:
i +=1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
# Example usage
arr = [10, 7, 8, 9, 1, 5]
quick_sort_pivot(arr, 0, len(arr)-1, pivot_type='first')
quick_sort_pivot(arr, 0, len(arr)-1, pivot_type='last')
quick_sort_pivot(arr, 0, len(arr)-1, pivot_type='random')
6. Finding kth Minimum and Maximum in Heap
import heapq
def kth_min(arr, k):
return heapq.nsmallest(k, arr)[-1]
def kth_max(arr, k):
return heapq.nlargest(k, arr)[-1]
# Example usage
arr = [12, 3, 5, 7, 19]
k = 2
min_k = kth_min(arr, k)
max_k = kth_max(arr, k)
7. Quick Sort with Duplicate Numbers
def quick_sort_duplicates(arr, low, high):
if low < high:
pi = partition_duplicates(arr, low, high)
quick_sort_duplicates(arr, low, pi-1)
quick_sort_duplicates(arr, pi+1, high)
def partition_duplicates(arr, low, high):
pivot = arr[high]
i = low -1
for j in range(low, high):
if arr[j] <= pivot:
i +=1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
# Example usage
arr = [4, 2, 5, 2, 3, 3, 1]
quick_sort_duplicates(arr, 0, len(arr)-1)
8. Build Min Heap, Max Heap and Sort
import heapq
def build_min_heap(arr):
heapq.heapify(arr)
return arr
def build_max_heap(arr):
max_heap = []
for item in arr:
heapq.heappush(max_heap, -item)
return max_heap
def heap_sort_min(arr):
heapq.heapify(arr)
sorted_arr = []
while arr:
sorted_arr.append(heapq.heappop(arr))
return sorted_arr
def heap_sort_max(arr):
max_heap = build_max_heap(arr)
sorted_arr = []
while max_heap:
sorted_arr.append(-heapq.heappop(max_heap))
return sorted_arr
# Example usage
arr = [12, 11, 13, 5, 6, 7]
min_heap = build_min_heap(arr.copy())
max_heap = build_max_heap(arr.copy())
sorted_min = heap_sort_min(arr.copy())
sorted_max = heap_sort_max(arr.copy())
9. Priority Queue Using Heaps
import heapq
class PriorityQueue:
def __init__(self):
self.heap = []
def push(self, item):
heapq.heappush(self.heap, item)
def pop(self):
return heapq.heappop(self.heap)
def peek(self):
return self.heap[0] if self.heap else None
def is_empty(self):
return len(self.heap) == 0
# Example usage
pq = PriorityQueue()
pq.push(10)
pq.push(5)
pq.push(15)
top = pq.pop()
10. Find Maximum and Minimum Marks Using Heap
import heapq
def find_max_min(marks):
if not marks:
return None, None
min_heap = marks.copy()
heapq.heapify(min_heap)
min_mark = heapq.heappop(min_heap)
max_mark = max(marks)
return max_mark, min_mark
# Example usage
marks = [88, 92, 75, 63, 95, 85]
max_mark, min_mark = find_max_min(marks)
11. Delete kth Indexed Element in Min Heap and Max Heap
import heapq
def delete_kth_min(heap, k):
if k < 0 or k >= len(heap):
return heap
heap[k], heap[-1] = heap[-1], heap[k]
heap.pop()
heapq.heapify(heap)
return heap
def delete_kth_max(heap, k):
if k < 0 or k >= len(heap):
return heap
heap[k] = -heap[k]
heap[k], heap[-1] = heap[-1], heap[k]
heap.pop()
heapq.heapify(heap)
return heap
# Example usage
min_heap = [5, 10, 15, 20]
max_heap = [-20, -15, -10, -5]
min_heap = delete_kth_min(min_heap, 2)
max_heap = delete_kth_max(max_heap, 1)
12. Insertion Sort and Complexity Comparison
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j]:
arr[j+1] = arr[j]
j -=1
arr[j+1] = key
# Example usage
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
13. AVL Tree with Insertion, Deletion, and Searching
class AVLNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
def get_height(node):
if not node:
return 0
return node.height
def get_balance(node):
if not node:
return 0
return get_height(node.left) - get_height(node.right)
def right_rotate(z):
y = z.left
T3 = y.right
y.right = z
z.left = T3
z.height = 1 + max(get_height(z.left), get_height(z.right))
y.height = 1 + max(get_height(y.left), get_height(y.right))
return y
def left_rotate(z):
y = z.right
T2 = y.left
y.left = z
z.right = T2
z.height = 1 + max(get_height(z.left), get_height(z.right))
y.height = 1 + max(get_height(y.left), get_height(y.right))
return y
def insert_avl(node, key):
if not node:
return AVLNode(key)
elif key < node.key:
node.left = insert_avl(node.left, key)
else:
node.right = insert_avl(node.right, key)
node.height = 1 + max(get_height(node.left), get_height(node.right))
balance = get_balance(node)
if balance > 1 and key < node.left.key:
return right_rotate(node)
if balance < -1 and key > node.right.key:
return left_rotate(node)
if balance > 1 and key > node.left.key:
node.left = left_rotate(node.left)
return right_rotate(node)
if balance < -1 and key < node.right.key:
node.right = right_rotate(node.right)
return left_rotate(node)
return node
def min_value_node(node):
current = node
while current.left:
current = current.left
return current
def delete_avl(node, key):
if not node:
return node
elif key < node.key:
node.left = delete_avl(node.left, key)
elif key > node.key:
node.right = delete_avl(node.right, key)
else:
if not node.left:
temp = node.right
node = None
return temp
elif not node.right:
temp = node.left
node = None
return temp
temp = min_value_node(node.right)
node.key = temp.key
node.right = delete_avl(node.right, temp.key)
if not node:
return node
node.height = 1 + max(get_height(node.left), get_height(node.right))
balance = get_balance(node)
if balance > 1 and get_balance(node.left) >=0:
return right_rotate(node)
if balance >1 and get_balance(node.left)<0:
node.left = left_rotate(node.left)
return right_rotate(node)
if balance < -1 and get_balance(node.right) <=0:
return left_rotate(node)
if balance < -1 and get_balance(node.right)>0:
node.right = right_rotate(node.right)
return left_rotate(node)
return node
def search_avl(node, key):
if node is None or node.key == key:
return node
if key < node.key:
return search_avl(node.left, key)
return search_avl(node.right, key)
# Example usage
root = None
keys = [10, 20, 30, 40, 50, 25]
for key in keys:
root = insert_avl(root, key)
root = delete_avl(root, 40)
found = search_avl(root, 25)
14. Red-Black Tree and Its Operations
class RBNode:
def __init__(self, key):
self.key = key
self.left = self.right = self.parent = None
self.color = 1
class RedBlackTree:
def __init__(self):
self.TNULL = RBNode(0)
self.TNULL.color = 0
self.root = self.TNULL
def insert(self, key):
node = RBNode(key)
node.parent = None
node.left = self.TNULL
node.right = self.TNULL
node.color = 1
y = None
x = self.root
while x != self.TNULL:
y = x
if node.key < x.key:
x = x.left
else:
x = x.right
node.parent = y
if y == None:
self.root = node
elif node.key < y.key:
y.left = node
else:
y.right = node
if node.parent == None:
node.color = 0
return
if node.parent.parent == None:
return
self.fix_insert(node)
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left != self.TNULL:
y.left.parent = x
y.parent = x.parent
if x.parent == None:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
def right_rotate(self, x):
y = x.left
x.left = y.right
if y.right != self.TNULL:
y.right.parent = x
y.parent = x.parent
if x.parent == None:
self.root = y
elif x == x.parent.right:
x.parent.right = y
else:
x.parent.left = y
y.right = x
x.parent = y
def fix_insert(self, k):
while k.parent.color == 1:
if k.parent == k.parent.parent.right:
u = k.parent.parent.left
if u.color == 1:
u.color = 0
k.parent.color = 0
k.parent.parent.color = 1
k = k.parent.parent
else:
if k == k.parent.left:
k = k.parent
self.right_rotate(k)
k.parent.color = 0
k.parent.parent.color = 1
self.left_rotate(k.parent.parent)
else:
u = k.parent.parent.right
if u.color ==1:
u.color =0
k.parent.color =0
k.parent.parent.color =1
k = k.parent.parent
else:
if k == k.parent.right:
k = k.parent
self.left_rotate(k)
k.parent.color =0
k.parent.parent.color =1
self.right_rotate(k.parent.parent)
if k == self.root:
break
self.root.color = 0
def search_tree_helper(self, node, key):
if node == self.TNULL or key == node.key:
return node
if key < node.key:
return self.search_tree_helper(node.left, key)
return self.search_tree_helper(node.right, key)
def search(self, key):
return self.search_tree_helper(self.root, key)
# Example usage
rbt = RedBlackTree()
keys = [20, 15, 25, 10, 5]
for key in keys:
rbt.insert(key)
found = rbt.search(15)
15. B-Tree and Its Operations
class BTreeNode:
def __init__(self, t, leaf=False):
self.t = t
self.leaf = leaf
self.keys = []
self.children = []
class BTree:
def __init__(self, t):
self.root = BTreeNode(t, True)
self.t = t
def insert(self, key):
root = self.root
if len(root.keys) == (2*self.t)-1:
temp = BTreeNode(self.t, False)
temp.children.insert(0, self.root)
self.split_child(temp, 0)
self.insert_non_full(temp, key)
self.root = temp
else:
self.insert_non_full(root, key)
def insert_non_full(self, node, key):
i = len(node.keys)-1
if node.leaf:
node.keys.append(None)
while i >=0 and key < node.keys[i]:
node.keys[i+1] = node.keys[i]
i -=1
node.keys[i+1] = key
else:
while i >=0 and key < node.keys[i]:
i -=1
i +=1
if len(node.children[i].keys) == (2*self.t)-1:
self.split_child(node, i)
if key > node.keys[i]:
i +=1
self.insert_non_full(node.children[i], key)
def split_child(self, parent, i):
t = self.t
y = parent.children[i]
z = BTreeNode(t, y.leaf)
parent.keys.insert(i, y.keys[t-1])
parent.children.insert(i+1, z)
z.keys = y.keys[t:(2*t-1)]
y.keys = y.keys[0:t-1]
if not y.leaf:
z.children = y.children[t:(2*t)]
y.children = y.children[0:t]
def search(self, key, node=None):
if node is None:
node = self.root
i = 0
while i < len(node.keys) and key > node.keys[i]:
i +=1
if i < len(node.keys) and key == node.keys[i]:
return node
if node.leaf:
return None
return self.search(key, node.children[i])
# Example usage
bt = BTree(3)
keys = [10, 20, 5, 6, 12, 30, 7, 17]
for key in keys:
bt.insert(key)
found = bt.search(6)
16. Naïve Search for Pattern Matching
def naive_search(text, pattern):
n = len(text)
m = len(pattern)
for i in range(n - m +1):
j =0
while j < m and text[i+j] == pattern[j]:
j +=1
if j == m:
return i
return -1
# Example usage
text = "hello world"
pattern = "world"
index = naive_search(text, pattern)
17. Rabin-Karp Algorithm for Pattern Matching
def rabin_karp(text, pattern, d=256, q=101):
n = len(text)
m = len(pattern)
h = pow(d, m-1) % q
p = 0
t =0
for i in range(m):
p = (d*p + ord(pattern[i])) % q
t = (d*t + ord(text[i])) % q
for i in range(n - m +1):
if p == t:
if text[i:i+m] == pattern:
return i
if i < n - m:
t = (d*(t - ord(text[i])*h) + ord(text[i+m])) % q
if t <0:
t += q
return -1
# Example usage
text = "abracadabra"
pattern = "cad"
index = rabin_karp(text, pattern)
18. Knuth-Morris-Pratt (KMP) Algorithm for Pattern Matching
def compute_lps(pattern):
lps = [0]*len(pattern)
length =0
i =1
while i < len(pattern):
if pattern[i] == pattern[length]:
length +=1
lps[i] = length
i +=1
else:
if length !=0:
length = lps[length-1]
else:
lps[i] =0
i +=1
return lps
def kmp_search(text, pattern):
n = len(text)
m = len(pattern)
lps = compute_lps(pattern)
i = j =0
while i < n:
if pattern[j] == text[i]:
i +=1
j +=1
if j == m:
return i-j
elif i < n and pattern[j] != text[i]:
if j !=0:
j = lps[j-1]
else:
i +=1
return -1
# Example usage
text = "abxabcabcaby"
pattern = "abcaby"
index = kmp_search(text, pattern)
19. Approximate Algorithm for Vertex Cover Problem
def vertex_cover_approx(graph):
cover = set()
edges = set()
for u in graph:
for v in graph[u]:
if (v, u) not in edges:
edges.add((u, v))
while edges:
u, v = edges.pop()
cover.add(u)
cover.add(v)
edges = set([(x, y) for (x, y) in edges if x != u and y != u and x != v and y != v])
return cover
# Example usage
graph = {
0: [1, 2],
1: [0, 2, 3],
2: [0, 1, 3],
3: [1, 2]
}
cover = vertex_cover_approx(graph)
20. Approximate Algorithm for Subset Sum Problem
def subset_sum_approx(arr, target):
arr = sorted(arr, reverse=True)
subset = []
total =0
for num in arr:
if total + num <= target:
subset.append(num)
total += num
if total == target:
break
return subset
# Example usage
arr = [3, 34, 4, 12, 5, 2]
target = 9
subset = subset_sum_approx(arr, target)
21. Binomial Heap and Its Operations
class BinomialNode:
def __init__(self, key):
self.key = key
self.degree =0
self.parent = None
self.child = None
self.sibling = None
class BinomialHeap:
def __init__(self):
self.head = None
def merge_roots(self, h1, h2):
if h1 is None:
return h2
if h2 is None:
return h1
if h1.degree <= h2.degree:
res = h1
res.sibling = self.merge_roots(h1.sibling, h2)
else:
res = h2
res.sibling = self.merge_roots(h1, h2.sibling)
return res
def union(self, h2):
self.head = self.merge_roots(self.head, h2.head)
if self.head is None:
return
prev = None
curr = self.head
next = curr.sibling
while next:
if curr.degree != next.degree or (next.sibling and next.sibling.degree == curr.degree):
prev = curr
curr = next
else:
if curr.key <= next.key:
curr.sibling = next.sibling
self.link(next, curr)
else:
if prev is None:
self.head = next
else:
prev.sibling = next
self.link(curr, next)
curr = next
next = curr.sibling
def link(self, y, z):
y.parent = z
y.sibling = z.child
z.child = y
z.degree +=1
def insert(self, key):
h = BinomialHeap()
h.head = BinomialNode(key)
self.union(h)
def find_min(self):
y = None
x = self.head
min_key = float('inf')
while x:
if x.key < min_key:
min_key = x.key
y = x
x = x.sibling
return y
def extract_min(self):
if self.head is None:
return None
prev_min = None
min_node = self.head
prev = None
curr = self.head
while curr:
if curr.key < min_node.key:
min_node = curr
prev_min = prev
prev = curr
curr = curr.sibling
if prev_min:
prev_min.sibling = min_node.sibling
else:
self.head = min_node.sibling
child = min_node.child
new_heap = BinomialHeap()
children = []
while child:
next_child = child.sibling
child.sibling = None
child.parent = None
children.insert(0, child)
child = next_child
for c in children:
new_heap.insert(c.key)
self.union(new_heap)
return min_node.key
def find_min_heap(self):
return self.find_min()
def union_heaps(self, other):
self.union(other)
# Example usage
bh1 = BinomialHeap()
bh1.insert(10)
bh1.insert(20)
bh2 = BinomialHeap()
bh2.insert(5)
bh2.insert(15)
bh1.union_heaps(bh2)
min_val = bh1.find_min()
extracted = bh1.extract_min()
22. Fibonacci Heap and Its Operations
class FibonacciNode:
def __init__(self, key):
self.key = key
self.degree =0
self.parent = None
self.child = None
self.left = self.right = self
self.mark = False
class FibonacciHeap:
def __init__(self):
self.min = None
self.count =0
def insert(self, key):
node = FibonacciNode(key)
if self.min is None:
self.min = node
else:
node.left = self.min
node.right = self.min.right
self.min.right.left = node
self.min.right = node
if key < self.min.key:
self.min = node
self.count +=1
def find_min(self):
return self.min
def union(self, other):
if other.min is None:
return
if self.min is None:
self.min = other.min
self.count = other.count
else:
self.min.right.left = other.min.left
other.min.left.right = self.min.right
self.min.right = other.min
other.min.left = self.min
if other.min.key < self.min.key:
self.min = other.min
self.count += other.count
def extract_min(self):
z = self.min
if z is not None:
if z.child is not None:
children = []
c = z.child
while True:
children.append(c)
c = c.right
if c == z.child:
break
for child in children:
child.left.right = child.right
child.right.left = child.left
child.left = self.min
child.right = self.min.right
self.min.right.left = child
self.min.right = child
child.parent = None
z.left.right = z.right
z.right.left = z.left
if z == z.right:
self.min = None
else:
self.min = z.right
self.consolidate()
self.count -=1
return z.key if z else None
def consolidate(self):
import math
array_size = int(math.log(self.count, 2)) +1
A = [None]*array_size
roots = []
x = self.min
if x:
while True:
roots.append(x)
x = x.right
if x == self.min:
break
for w in roots:
x = w
d = x.degree
while A[d] is not None:
y = A[d]
if x.key > y.key:
x, y = y, x
self.link(y, x)
A[d] = None
d +=1
A[d] = x
self.min = None
for i in range(array_size):
if A[i] is not None:
if self.min is None:
self.min = A[i]
A[i].left = A[i].right = A[i]
else:
A[i].left = self.min
A[i].right = self.min.right
self.min.right.left = A[i]
self.min.right = A[i]
if A[i].key < self.min.key:
self.min = A[i]
def link(self, y, x):
y.left.right = y.right
y.right.left = y.left
y.parent = x
if x.child is None:
x.child = y
y.right = y.left = y
else:
y.left = x.child
y.right = x.child.right
x.child.right.left = y
x.child.right = y
x.degree +=1
y.mark = False
# Example usage
fh = FibonacciHeap()
fh.insert(10)
fh.insert(20)
fh.insert(5)
min_val = fh.find_min()
extracted = fh.extract_min()
23. Approximate Algorithm for Traveling Salesman Problem
def tsp_approx(graph, start):
n = len(graph)
visited = [False]*n
path = []
current = start
path.append(current)
visited[current] = True
while len(path) < n:
next_city = None
min_dist = float('inf')
for city in range(n):
if not visited[city] and graph[current][city] < min_dist:
min_dist = graph[current][city]
next_city = city
if next_city is None:
break
path.append(next_city)
visited[next_city] = True
current = next_city
path.append(start)
return path
# Example usage
graph = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
tour = tsp_approx(graph, 0)
24. Approximate Algorithm for Vertex Cover Problem
def vertex_cover_approx(graph):
cover = set()
edges = set()
for u in graph:
for v in graph[u]:
if (v, u) not in edges:
edges.add((u, v))
while edges:
u, v = edges.pop()
cover.add(u)
cover.add(v)
edges = set([(x, y) for (x, y) in edges if x != u and y != u and x != v and y != v])
return cover
# Example usage
graph = {
0: [1, 2],
1: [0, 2, 3],
2: [0, 1, 3],
3: [1, 2]
}
cover = vertex_cover_approx(graph)
25. Approximate Algorithm for Subset Sum Problem
def subset_sum_approx(arr, target):
arr = sorted(arr, reverse=True)
subset = []
total =0
for num in arr:
if total + num <= target:
subset.append(num)
total += num
if total == target:
break
return subset
# Example usage
arr = [3, 34, 4, 12, 5, 2]
target = 9
subset = subset_sum_approx(arr, target)
You can copy each code block into your .docx file as needed.