在一维数据中,peak是指某个数组元素大于它前后的数组元素,例如数组:A = {2,6,7,8,4,78,33},其中8和78分别称为peak。对于数据的边界元素来讲,由于与它相邻的元素只有一个,因此只要它大于与它相邻的那个元素,那么它也被认为是一个peak。
本文讲的peak finding算法是指在一个一维数组中如何快速找到一个peak,而不是寻找出数组中的所有peak。
首先来介绍一个简单粗暴的算法,就是按顺序扫描数组元素,直到找到一个peak为止,具体代码如下:
def algorithm1(array):
#如果数组为空,则结束。
if len(array) <= 0:
return None
count = 0
while(count < len(array)):
testElem = array[count]
if count == 0:
adjacentElem = array[count + 1]
if testElem >= adjacentElem:
return testElem
elif count == len(array) - 1:
adjacengElem = array[count - 1]
if testElem >= adjacentElem:
return testElem
else: