May 29, 2024
O(1)
O(log n)
O(n)
O(n²)
O(n³)
O(n log n)
O(2^n)
O(n!)
# Linear Search Implementation
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return None
# Binary Search Implementation
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return None
# Recursive Sum Function
def recursive_sum(arr):
if not arr:
return 0
return arr[0] + recursive_sum(arr[1:])
# Merge Sort Implementation
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
sorted_arr = []
while left and right:
if left[0] < right[0]:
sorted_arr.append(left.pop(0))
else:
sorted_arr.append(right.pop(0))
sorted_arr.extend(left or right)
return sorted_arr
# Quick Sort Implementation
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# Node class for linked list
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __repr__(self):
return f"Node({self.data})"
# Linked list class
class LinkedList:
def __init__(self):
self.head = None
def is_empty(self):
return self.head is None
def size(self):
current = self.head
count = 0
while current:
count += 1
current = current.next
return count
def add(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def search(self, key):
current = self.head
while current and current.data != key:
current = current.next
return current
def remove(self, key):
current = self.head
previous = None
found = False
while current and not found:
if current.data == key:
found = True
else:
previous = current
current = current.next
if current is None:
return None
if previous is None:
self.head = current.next
else:
previous.next = current.next
return current
O(n)
O(log n)
O(n²)
O(n log n)
O(n log n)
, Worst-case O(n²)
depending on pivot choice