Introduction to Algorithms
What are algorithms and why they matter
What is an Algorithm?##
An algorithm is a step-by-step procedure for solving a problem or accomplishing a task.
Time Complexity###
The most common way to measure algorithm efficiency is Big O notation:
| Notation | Name | Example |
|---|---|---|
| O(1) | Constant | Hash table lookup |
| O(log n) | Logarithmic | Binary search |
| O(n) | Linear | Linear search |
| O(n log n) | Linearithmic | Merge sort |
| O(n²) | Quadratic | Bubble sort |
# Example: Binary Search
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