An algorithm is a step-by-step procedure to perform a task.
Used in computing for:
Finding shortest paths in graphs (e.g., GPS navigation).
Searching for patterns (e.g., Google Search).
Sorting and searching operations.
Total order: A system where every pair of elements has a defined comparison (greater/lesser).
Examples:
Numbers: 1<2<31 < 2 < 31<2<3
Words: Alphabetical order (e.g., "forest" < "forever").
Divides the list into:
Sorted sublist (left).
Unsorted sublist (right).
Steps:
Find the smallest element in the unsorted sublist.
Swap it with the leftmost unsorted element.
Move boundary between sorted/unsorted sublists.
Repeat until the list is sorted.
Example: Sorting [5,4,3,7,1]
Pass 1: [1,4,3,7,5]
Pass 2: [1,3,4,7,5]
Pass 3: [1,3,4,7,5]
Pass 4: [1,3,4,5,7]
Final: [1,3,4,5,7]
Time Complexity:
O(n2)O(n^2)O(n2) (quadratic time)
Steps:
Compare each element with its neighbor.
Swap if the left element is greater.
Repeat passes until the list is sorted.
Example: Sorting [5,4,3,7,1]
Pass 1: [4,3,5,1,7]
Pass 2: [3,4,1,5,7]
Pass 3: [3,1,4,5,7]
Pass 4: [1,3,4,5,7] ✅ Sorted!
Time Complexity:
O(n2)O(n^2)O(n2) (quadratic time)
Note: Bubble Sort is inefficient compared to other sorting algorithms.
Faster than linear search.
Steps:
Check the middle element.
If it's equal to the target, return the index.
If it's smaller, search the right half.
If it's larger, search the left half.
Repeat until found or list is empty.
Example: Find 7 in [-3, -1, 4, 6, 8, 12, 15, 23, 24]
Middle = 6 → 7 is larger → Search right half.
New Middle = 12 → 7 is smaller → Search left half.
New Middle = 8 → 7 is smaller → Search left half.
Empty list → 7 is not found.
Time Complexity:
Best case: O(1)O(1)O(1) (if found immediately).
Worst case: O(logn)O(\log n)O(logn) (logarithmic time).
Used in:
Dictionaries (finding words quickly).
Large datasets (faster search).