-->
Arrays
array = [1, 2, 3, 4, 5]
print(array[2]) # Access element at index 2
Linked Lists
class Node:
def __init__(self, value):
self.value = value
self.next = None
head = Node(1)
head.next = Node(2)
Stacks
stack = []
stack.append(1) # Push
print(stack.pop()) # Pop
Queues
from collections import deque
queue = deque()
queue.append(1) # Enqueue
print(queue.popleft()) # Dequeue
Hash Tables
hash_table = {}
hash_table['key'] = 'value'
print(hash_table['key']) # Access by key
Trees
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
Sorting Algorithms
Bubble Sort:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
array = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(array)
print(array)
Quick Sort:
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)
array = [3, 6, 8, 10, 1, 2, 1]
print(quick_sort(array))
Searching Algorithms
Linear Search:
def linear_search(arr, target):
for i, value in enumerate(arr):
if value == target:
return i
return -1
array = [1, 3, 5, 7, 9]
print(linear_search(array, 5)) # Output: 2
Binary Search:
def binary_search(arr, target):
low, high = 0, 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 -1
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(binary_search(array, 4)) # Output: 3
Graph Algorithms
Depth-First Search (DFS):
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for next_node in graph[start] - visited:
dfs(graph, next_node, visited)
return visited
graph = {'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}}
print(dfs(graph, 'A'))
Breadth-First Search (BFS):
def bfs(graph, start):
visited, queue = set(), [start]
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited
graph = {'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}}
print(bfs(graph, 'A'))
Understanding and implementing these basic data structures and algorithms are essential steps towards solving complex computational problems. By mastering these fundamentals, one can efficiently manage data, optimize performance, and develop robust applications.