I might propose something like this instead:
Code:
#include <stdio.h>
#include <stddef.h>
size_t identifyPeaks(double points[], size_t num_points, double peaks[]);
int main(void)
{
double points[] = {1, 2, 2, 4, 2, 2, 1, 2, 2, 1, 2.1, 2, 2, 1,2, 2, 3.5, 2, 2, 1};
double peaks[sizeof(points) / sizeof(points[0])];
size_t num_peaks = identifyPeaks(points, sizeof(points) / sizeof(points[0]), peaks);
size_t i;
for (i = 0; i < num_peaks; ++i)
{
printf("%f ", peaks[i]);
}
putchar('\n');
return 0;
}
size_t identifyPeaks(double points[], size_t num_points, double peaks[])
{
size_t num_peaks = 0;
size_t i;
for (i = 1; i < num_points - 1; ++i)
{
if (points[i] > points[i - 1] && points[i] > points[i + 1])
{
peaks[num_peaks++] = points[i];
}
}
return num_peaks;
}
Basically, my idea is to compare the current element with its neighbours. If it is strictly greater than its immediate neighbours, it is classified as a peak and added to the result array.
Of course, this is rather naive, e.g., if you have two values at a plateau, neither will be identified as a peak. This could be problematic if the input represents a square sine wave.