Search Algorithms
Linear Search
Bisection/binary search
divide and conquer
Linear search
on a SORTED list
- O(n) - where n is len(L)
Bisection search
- answer to smaller version is answer to original problem
Searching a sorted list
n is len(L)
When to sort first then search?
Amortized cost
n is len(L)
Monkey Sort
aka bogosort - stupid sort - slowsort - permutation sort - shotgun sort
is a random sort, every time through the list get randomly sorted and if lucky it is ordered!
Monkey Sort - complexity
Best case:
O(n) where n is len(L)
Worst case:
O(?) is unbound if really unlucky
Bubble Sort
Bubble Sort - complexity
Selection Sort
1. First step
- swap it with element at index 0
Selection Sort
2. Subsequent step
- swap it with the element at index 1
Selection Sort
3. Keep the left portion of the list sorted
- all other elements are bigger than first i elements
Selection Sort - complexity
O(n2) where n is len(L)
Merge Sort
Use a divide-and-conquer approach
Merge Sort - complexity
overview
Merge Sort - recursevely
- depth-first such that conquer smallest pieces down one branch first before moving to larger pieces
Merge Sort - complexity
1. at first recursion level
- O(n) + O(n) where n is len(L)
Merge Sort - complexity
2. at second recursion level
Merge Sort - complexity
3. dividing list in half
with each recursive call:
O(log(n)) where n is len(L)
Merge Sort - complexity
O(n log (n)) where n is len(L)
Sorting Summary
n is len(L)
bogo sort - randomness, unbound O() bubble sort - O(n2) selection sort - O(n2) - guaranteed the first i elements were sorted merge sort - O(n log(n)) O(n log(n)) is the fastest a sort can be