# Catatan Seekor Algorithm

Algoritma adalah serangkaian langkah-langkah yang terstruktur dan logis untuk menyelesaikan masalah atau mencapai tujuan tertentu dalam pemrograman.

## Fundamental Concepts

### Algorithm Analysis

* **Time Complexity**: Berapa lama algoritma berjalan
* **Space Complexity**: Berapa banyak memori yang dibutuhkan
* **Big O Notation**: Cara mengukur efisiensi algoritma

### Complexity Classes

```
O(1)     - Constant time
O(log n) - Logarithmic time
O(n)     - Linear time
O(n log n) - Linearithmic time
O(n²)    - Quadratic time
O(2ⁿ)    - Exponential time
O(n!)    - Factorial time
```

## Sorting Algorithms

### Bubble Sort

```python
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]
    return arr

# Time Complexity: O(n²)
# Space Complexity: O(1)
```

### Selection Sort

```python
def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr

# Time Complexity: O(n²)
# Space Complexity: O(1)
```

### Insertion Sort

```python
def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr

# Time Complexity: O(n²)
# Space Complexity: O(1)
```

### Merge Sort

```python
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):
    result = []
    i = j = 0
    
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    
    result.extend(left[i:])
    result.extend(right[j:])
    return result

# Time Complexity: O(n log n)
# Space Complexity: O(n)
```

### Quick Sort

```python
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)

# Time Complexity: O(n log n) average, O(n²) worst case
# Space Complexity: O(log n)
```

## Searching Algorithms

### Linear Search

```python
def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

# Time Complexity: O(n)
# Space Complexity: O(1)
```

### Binary Search

```python
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    
    return -1

# Time Complexity: O(log n)
# Space Complexity: O(1)
```

### Binary Search Tree Search

```python
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

def search_bst(root, key):
    if root is None or root.key == key:
        return root
    
    if key < root.key:
        return search_bst(root.left, key)
    
    return search_bst(root.right, key)

# Time Complexity: O(h) where h is height of tree
# Space Complexity: O(h) for recursive calls
```

## Data Structures

### Linked List

```python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
    
    def insert_at_beginning(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node
    
    def insert_at_end(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node
    
    def delete_node(self, key):
        current = self.head
        
        if current and current.data == key:
            self.head = current.next
            return
        
        while current and current.next:
            if current.next.data == key:
                current.next = current.next.next
                return
            current = current.next
```

### Stack

```python
class Stack:
    def __init__(self):
        self.items = []
    
    def push(self, item):
        self.items.append(item)
    
    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        raise IndexError("Stack is empty")
    
    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        raise IndexError("Stack is empty")
    
    def is_empty(self):
        return len(self.items) == 0
    
    def size(self):
        return len(self.items)

# Time Complexity: O(1) for push, pop, peek
# Space Complexity: O(n)
```

### Queue

```python
from collections import deque

class Queue:
    def __init__(self):
        self.items = deque()
    
    def enqueue(self, item):
        self.items.append(item)
    
    def dequeue(self):
        if not self.is_empty():
            return self.items.popleft()
        raise IndexError("Queue is empty")
    
    def front(self):
        if not self.is_empty():
            return self.items[0]
        raise IndexError("Queue is empty")
    
    def is_empty(self):
        return len(self.items) == 0
    
    def size(self):
        return len(self.items)

# Time Complexity: O(1) for enqueue, dequeue, front
# Space Complexity: O(n)
```

## Graph Algorithms

### Depth-First Search (DFS)

```python
def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    
    visited.add(start)
    print(start, end=' ')
    
    for neighbor in graph[start]:
        if neighbor not in visited:
            dfs(graph, neighbor, visited)

# Example usage
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F'],
    'D': ['B'],
    'E': ['B', 'F'],
    'F': ['C', 'E']
}

# Time Complexity: O(V + E) where V is vertices, E is edges
# Space Complexity: O(V) for visited set
```

### Breadth-First Search (BFS)

```python
from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    visited.add(start)
    
    while queue:
        vertex = queue.popleft()
        print(vertex, end=' ')
        
        for neighbor in graph[vertex]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

# Time Complexity: O(V + E)
# Space Complexity: O(V) for queue and visited set
```

### Dijkstra's Shortest Path

```python
import heapq

def dijkstra(graph, start):
    distances = {vertex: float('infinity') for vertex in graph}
    distances[start] = 0
    pq = [(0, start)]
    
    while pq:
        current_distance, current_vertex = heapq.heappop(pq)
        
        if current_distance > distances[current_vertex]:
            continue
        
        for neighbor, weight in graph[current_vertex].items():
            distance = current_distance + weight
            
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(pq, (distance, neighbor))
    
    return distances

# Time Complexity: O((V + E) log V) with binary heap
# Space Complexity: O(V)
```

## Dynamic Programming

### Fibonacci with Memoization

```python
def fibonacci_memo(n, memo={}):
    if n in memo:
        return memo[n]
    if n <= 1:
        return n
    
    memo[n] = fibonacci_memo(n-1, memo) + fibonacci_memo(n-2, memo)
    return memo[n]

# Time Complexity: O(n)
# Space Complexity: O(n)
```

### Longest Common Subsequence

```python
def lcs(str1, str2):
    m, n = len(str1), len(str2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if str1[i-1] == str2[j-1]:
                dp[i][j] = dp[i-1][j-1] + 1
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])
    
    return dp[m][n]

# Time Complexity: O(mn)
# Space Complexity: O(mn)
```

## Best Practices

### Algorithm Design

* **Understand the Problem**: Clearly define input, output, and constraints
* **Choose Appropriate Data Structures**: Select structures that optimize operations
* **Consider Edge Cases**: Handle empty inputs, invalid data, etc.
* **Optimize for Readability**: Write clear, maintainable code

### Performance Optimization

* **Profile Your Code**: Identify bottlenecks
* **Use Efficient Algorithms**: Choose appropriate complexity classes
* **Optimize Critical Paths**: Focus on frequently executed code
* **Consider Memory Usage**: Balance time and space complexity

### Testing

* **Unit Tests**: Test individual functions
* **Edge Cases**: Test boundary conditions
* **Performance Tests**: Verify complexity expectations
* **Integration Tests**: Test algorithm interactions
