⬅️ CS50
Big O notation (O)
- for describing the running time of algorithms (how many steps max will it take)
O(n)
- on the order of n
🤔 And what’s in the opposite end of Big O?
Ω
Greek Omega letter used to describe the best-case scenario (Ω of …)- They are both approximations
Linear search
- Iterate across the array from left to right, trying to find the target element.
Binary search
- Given a sorted array, divide and conquer by systematically eliminating half of the remaining elements (phone book) in the search for the target element.
Sorting
- In C you can’t use double equal to compare two strings (yes for
int
and yes forchar
) - instead you have to use a function like
strcmp()
found in<string.h>
file
🤔 What’s a hertz?
- something that is done once per second
- if your computer’s CPU is 1 gigahertz, that means that it can do 1 billion things at a time
Custom types
🤔 What is a struct? It’s a container inside which you can put multiple other data types.
Selection sort
- Find the smallest unsorted element in an array and swap it with the first unsorted element of that array.
- The amount of work will decrease with each iteration.
- However, you can’t short circuit and quit the work even if all the elements are already swapped
Bubble sort
- Swap the adjacent pairs of elements if they are out of order, effectively bubbling larger elements to the right and smaller ones to the left.
Merge sort
- Split the full array into subarrays, then merge those subarrays back together in the correct order.
- Meaning that in an array of size 8, you’ll start with 8 lists of size 1
- You’ll need some temporary arrays to help you with sorting, meaning you’ll be needing at least twice as much space
Insertion sort
- Proceed once through the array from left to right, shifting elements as necessary to insert each element into its correct place.
🤔 How do the algorithms compare In terms of running time (slowest → fastest)?
In terms of Big O:
O(n2)
bubble sort, selection sort, insertion sortO(n log n)
merge sortO(n)
linear searchO(log n)
binary searchO(1)
In terms of Ω:
Ω(n2)
selection sortΩ(n log n)
merge sortΩ(n)
bubble sort, insertion sortΩ(log n)
Ω(1)
linear search, binary search
θ Theta
for describing algorithms where O
andΩ
values are the same
θ(n2)
selection sortθ(n log n)
merge sortθ(n)
θ(log n)
θ(1)
Recursion
-
A function calling itself.
-
Classic example is the factorial:
fact(n) = n * fact(n-1)
Every factorial has two cases:
- base case: when triggered, will terminate the recursive process
- recursive case: which is where recursion actually occurs