Lecture3 PDF
Lecture3 PDF
input → → output
→ → output
→ → bool
algorithms
linear search
For i from 0 to n-1
If i'th element is 50
Return true
Return false
binary search
If middle item is 50
Return true
Else if 50 < middle item
Search left half
Else if 50 > middle item
Search right half
If no items
If middle item is 50
Return true
Else if 50 < middle item
Search left half
Else if 50 > middle item
Search right half
If no items
Return false
If middle item is 50
Return true
Else if 50 < middle item
Search left half
Else if 50 > middle item
Search right half
time to solve
size of problem
O(n) O(n/2)
time to solve
O(log2n)
size of problem
O
O(n) O(n/2)
time to solve
O(log2n)
size of problem
O(n) O(n/2)
time to solve
O(log2n)
size of problem
O(n) O(n)
time to solve
O(log2n)
size of problem
O(n) O(n)
time to solve
O(log n)
size of problem
O(n)
time to solve
O(log n)
size of problem
O(n2)
O(n log n)
O(n)
O(log n)
O(1)
O(n2)
O(n log n)
O(log n)
O(1)
O(n2)
O(n log n)
O(1)
Ω
Ω(n2)
Ω(n log n)
Ω(n)
Ω(log n)
Ω(1)
Ω(n2)
Ω(n log n)
Ω(n)
Ω(log n)
Ω(n log n)
Ω(n)
Ω(log n)
n2 – 1n – 1n + 1
(n – 1) × (n – 1)
n2 – 1n – 1n + 1
n2 – 2n + 1
(n – 1) × (n – 1)
n2 – 1n – 1n + 1
n2 – 2n + 1
O(n2)
O(n2)
O(n log n)
O(1)
O(n2) bubble sort
O(n log n)
O(1)
Ω
Repeat n-1 times
For i from 0 to n-2
If i'th and i+1'th elements out of order
Swap them
Ω(n2)
Ω(n log n)
Ω(n)
Ω(log n)
Ω(n log n)
Ω(n)
Ω(log n)
n(n + 1)/2
n + (n – 1) + (n – 2) + ... + 1
n(n + 1)/2
(n2 + n)/2
n + (n – 1) + (n – 2) + ... + 1
n(n + 1)/2
(n2 + n)/2
n2/2 + n/2
n + (n – 1) + (n – 2) + ... + 1
n(n + 1)/2
(n2 + n)/2
n2/2 + n/2
O(n2)
O(n2) bubble sort
O(n log n)
O(1)
O(n2) bubble sort, selection sort
O(n log n)
O(1)
Ω
For i from 0 to n-1
Find smallest item between i'th item and last item
Swap smallest item with i'th item
Ω(n2) bubble sort
Ω(n log n)
Ω(n)
Ω(log n)
Ω(n log n)
Ω(n)
Ω(log n)
Ω(n log n)
Ω(n)
Ω(log n)
Ω(n log n)
Ω(log n)
4
5 2 6 3 8 1
4 7
5 2 6 3 8 1
4 7
5 2 6 3 8 1
4 7
5 2 6 3 8 1
4 7
5 2 6 3 8 1
4 7
5 6 3 8 1
4 7 2
6 3 8 1
4 7 2 5
6 3 8 1
4 7 2 5
6 3 8 1
4 7 5
2
6 3 8 1
7 5
2 4
6 3 8 1
2 4 5
6 3 8 1
2 4 5 7
6 3 8 1
2 4 5 7
6 3 8 1
2 4 5 7
6 3 8 1
2 4 5 7
6 3 8 1
2 4 5 7
6 3 8 1
2 4 5 7
6 8 1
2 4 5 7
8 1
3 6
2 4 5 7
8 1
3 6
2 4 5 7
8 1
3 6
2 4 5 7
8 1
3 6
2 4 5 7
8 1
3 6
2 4 5 7
8 1
3 6 1
2 4 5 7
1
3 6 1 8
2 4 5 7
1
3 6 1 8
2 4 5 7
1
3 6 8
2 4 5 7 1
1
6 8
2 4 5 7 1 3
1
2 4 5 7 1 3 6
1
2 4 5 7 1 3 6 8
1
2 4 5 7 1 3 6 8
1
2 4 5 7 3 6 8
1
1
4 5 7 3 6 8
1 2
1
4 5 7 6 8
1 2 3
1
5 7 6 8
1 2 3 4
1
7 6 8
1 2 3 4 5
1
7 8
1 2 3 4 5 6
1
1 2 3 4 5 6 7
1
1 2 3 4 5 6 7 8
7 4 5 2 6 3 8 11
7 4 5 2 6 3 8 11
4 7 2 5 3 6 1 88
7 4 5 2 6 3 8 11
4 7 2 5 3 6 1 88
2 4 5 7 1 3 6 8
7 4 5 2 6 3 8 11
4 7 2 5 3 6 1 88
2 4 5 7 1 3 6 8
1 2 3 4 5 6 7 8
O(n2) bubble sort, selection sort
O(n log n)
O(1)
O(n2) bubble sort, selection sort
O(1)
Ω(n2) selection sort
Ω(n log n)
Ω(log n)
Ω(log n)
Θ(n log n)
Θ(n)
Θ(log n)
Θ(1)
Θ(n2) selection sort
Θ(n)
Θ(log n)
Θ(1)
This is CS50