Академический Документы
Профессиональный Документы
Культура Документы
Question:
Given a sequence of numbers, design
an algorithm to find the maximum
number. Show your algorithm is
correct and analyze the time
complexity.
4 7 24 30 34 35 36 37 39 45 50
34 35 36 37 39 45 50 4 7 24 30
Question 1
34 35 36 37 39 45 50 4 7 24 30
Where?
34 35 36 37 39 45 50 4 7 24 30
4 7 24 30 34 35 36 37 39 45 50
Question 1
• Design an O(log n)-time algorithm to
find the minimum item.
50 50 50 50
45 45
40 39 40 39
36 37 36 37
34 35 34 35
30 30 30 30
24 24
20 20
10 10
7 7
4 4
0 0
1 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 6 7 8 9 10 11
Question 2
ComputeCount()
1. Input a positive integer n
2. Set count = 0 What’s the running time?
3. for j = 1, 2, …, n Θ(n)
4. if j is a factor of n Can it be
5. { Update count to becomefaster?
1 - count }
6. Output count
Question 2
• Design a faster algorithm that can
compute count.
– O( n ), O(log n), O(1)…
– Note: You can only use RAM operations.
– E.g., you cannot assume 2x or log x can be
computed in O(1) time.
• Explain why your algorithm is correct.
Question 2
• Hint:
What’s the physical meaning of count?
Question 3
BubbleSort(A)
1. for Phase k = 1, 2, …, n
2. for Position j = 1, 2, …, n - 1
3. if A[j] > A[j + 1]
4. { Swap the entries A[j] and A[j + 1] }
Example:
Given (2, 3, 6, 4, 0)
(2, 0), (3, 0), (6, 4), (6, 0), (4, 0) are inverted.
Question 3
• Show that the number of inverted
pairs is exactly equal to the number
of swaps when we perform
BubbleSort.
• Design an algorithm that counts the
number of inverted pairs in O(n log n)
time.
Question 3
• Hint:
Inverted pairs: 4
(for the
last part)
10 23 14 5 17 26 12 19