When we design an algorithm we are majorly concerned with two things:
Let me first define what is a peak, then we will try an find ways to "Find a peak if it exists"
Consider a 1D array of n elements: A = [ a1, a2, ...., an ], then ith element ai is a peak iff :
ai-1 le ai AND ai+1 le ai
A straightforward algorithm to do this would be:
import numpy as np
n = 20 # Number of elements in the array
# Generate a random array of 20 integers within range [0, 100]
a = np.random.randint(100, size = n)
for i in range(n-1):
if a[i] >= a[i+1]:
print("Peak is {} at position {}".format (a[i], i))
break
elif i == n-2:
print("Peak is {} at position {}".format (a[i+1], i+1))
In the above algorithm we can see that in worst case scenario (when the peak is the last element of the array) we need to make n comparisions, thus the time complexity in Big O notation is O(n)
For any programming job, knowledge of algorithms is a must. Thus, comes this post, a follow-up to the MIT 6.006 Introduction to Algorithms course. I will continue writing about different algorithms taught in the course and their analysis. I hope they help someone getting a better understanding and finally a job.
Your upvotes, and comments will help me stay motivated. Follow me to stay updated
Cheers
Seben OfNine