Searching ans Sorting Flashcards
Search algorithms Bisection Search Bogo Sort Bubble Sort Merge Sort
Search Algorithms
- method for finding an item or group of items
- Collections could be implicit
- Collections could be explicit
Linear Search
- brute force search
- list does not have to be sorted
- O(n) - where n is len(L)
Bisection/binary search
divide and conquer
- list MUST be sorted to give correct answer
Linear search
on a SORTED list
- must only look until reach a number greater than e
- O(n) - where n is len(L)
Bisection search
- break into smaller version of problems
- answer to smaller version is answer to original problem
Searching a sorted list
n is len(L)
- linear search => O(n)
- binary search => O(log n)
(assumes the list is sorted!)
When to sort first then search?
- sort + O(log n) < O(n) ->
sort < O(n) - O(log n) - when sorting is less than O(n) -> never true!
Amortized cost
n is len(L)
- why bother sorting first
- in some cases, may sort list once -> then many searches
- AMORTIZE cost of the sort over many searches
- SORT + KO(log n) < KO(n) -> for large K, SORT time becomes irrelevant
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
- Compare consecutive pairs of elements
- Swap elements such that smaller is first
- Start over when reach end of list
- No more swaps = stop
Bubble Sort - complexity
- inner for loop is doing comparisons
- out while loop is doing multiple passes until no more swaps
O(n2) where n is len(L)
Selection Sort
1. First step
- extract min. element
- swap it with element at index 0
Selection Sort
2. Subsequent step
- in remaining sub-list extract min. element
- swap it with the element at index 1
Selection Sort
3. Keep the left portion of the list sorted
- at ith step, first i element in list are sorted
- all other elements are bigger than first i elements