An algorithm is a step-by-step procedure for solving a problem. Two fundamental categories of algorithms studied in computing are searching algorithms and sorting algorithms.
Searching algorithms locate a specific element (the target) within a data structure.
Linear Search (also called Sequential Search) examines each element one by one from the beginning until the target is found or the list ends.
How it works:
Key properties:
Example: Finding the number 7 in the list [3, 9, 1, 7, 5]:
Binary Search uses a divide-and-conquer strategy. It repeatedly halves the search interval.
Prerequisite: The list must be sorted.
How it works:
low = 0, high = n - 1.mid = (low + high) / 2.list[mid] == target → found.target < list[mid] → search the lower half: set high = mid - 1.target > list[mid] → search the upper half: set low = mid + 1.low > high (not found).Key properties:
Example: Finding 7 in the sorted list [1, 3, 5, 7, 9]:
low=0, high=4, mid=2 → list[2]=5 → 7 > 5, so low=3low=3, high=4, mid=3 → list[3]=7 → found at index 3Sorting algorithms arrange elements of a list in a specific order (usually ascending or descending).
Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.
How it works:
Key property: After each pass, the next largest element is placed in its correct final position.
Example: Sorting [5, 3, 8, 1]:
[3, 5, 1, 8] → 8 is in place[3, 1, 5, 8] → 5 is in place[1, 3, 5, 8] → sorted!Selection Sort divides the list into a sorted and an unsorted part. It repeatedly selects the minimum element from the unsorted part and moves it to the end of the sorted part.
How it works:
Example: Sorting [64, 25, 12, 22]:
[12, 25, 64, 22][12, 22, 64, 25][12, 22, 25, 64] → sorted!Insertion Sort builds the sorted array one element at a time, similar to how you sort playing cards in your hand.
How it works:
Example: Sorting [4, 2, 7, 1]:
[2, 4, 7, 1][2, 4, 7, 1][1, 2, 4, 7] → sorted!| Algorithm | Type | Requires Sorted? | Best For |
|---|---|---|---|
| Linear Search | Searching | No | Small or unsorted lists |
| Binary Search | Searching | Yes | Large sorted lists |
| Bubble Sort | Sorting | — | Simple/educational use |
| Selection Sort | Sorting | — | Small lists |
| Insertion Sort | Sorting | — | Nearly sorted lists |