This week I started MIT OCW 6.006 lectures and in the first lecture the professor introduced peak-finding algorithm.
According to his definitions:
[a b c d e f g h i]
1 2 3 4 5 6 7 8 9
a-i are numbersPosition 2 is a peak if and only if b ≥ a and b ≥ c. Position 9 is a peak if i ≥ h
He proposes this algorithm to improve its complexity:
If a[n/2] < a[n/2 − 1] then only look at left half 1 . . . n/2 − − − 1 to look for peak
• Else if a[n/2] < a[n/2 + 1] then only look at right half n/2 + 1 . . . n to look for peak
• Else n/2 position is a peak: WHY?
a[n/2] ≥ a[n/2 − 1]
a[n/2] ≥ a[n/2 + 1]
However, what if I have this example array:
[9,8,7,6,5,2,3,1]
The algorithm would work like this:
Step 1: a[n/2] < a[n/2-1]? --> 6 < 7? --> yes, look at left half [9,8,7,6]
Step 2: a[n/2] < a[n/2-1]? --> 8 < 9? --> yes, look at left half [9,8]
Step 3: ???
No peak would be found, although there is a peak: [9,8,7,6,5,2,3,1]
I guess I am missing something, but i didn't figure out. Someone can explain me why it is not working?
I found this related question, but no answer: Peak finding algorithm