Sort Algo:
Sorting Algorithm Comparison Table :
Bubble Sort - Nested loop
for i in range(n):
for j in range(n-i-1):
If the array is already sorted:
[1, 2, 3, 4, 5]
the algorithm can stop after one pass.
Selection Sort - Find the smallest element and put it at the beginning.
Insertion Sort - key is the element we're trying to insert into the already-sorted portion.
Insertion Sort is actually useful when:
Data is almost sorted
Dataset is small.You need an in-place algorithm
Searching Algo:
Binary Search (The Gold Standard for Search) - Binary Search works on a sorted array.
Concept: Divide and conquer on a sorted list.
Step-by-Step Dry Run:
Start with low = 0, high = len - 1.
Find mid.
If target == mid, return.
If target < mid, high = mid - 1.
Else, low = mid + 1.
Linear Search
Linear Search means checking every element one by one until we find the target.
arr = [10, 25, 30, 45, 50]
target = 45
Basic Algorithm
For every element:
Check whether it equals the target.
If yes → return its index.
Otherwise continue.
If we reach the end → target doesn't exist.
Use it when:
- The array is unsorted
- The array is small
- You only need to search once
- Sorting the data isn't worth the cost
No comments:
Post a Comment