How would I find multiple peaks and valleys in an array of values?

I know how to get the maximum and minimum values- I just set a variable to zero and then loop through the whole array and change the variable to Mathf.Max(theMax,theArray*).*
Now I’m trying to find the second highest or lowest points, which obviously would be one of the two points immediately on either side of the peak or valley, but that’s not what I mean - I’m trying to find peaks and valleys in a sequence, but only the biggest 2 or 3. And it’s getting messy.
I know this is more a general programming problem than a Unity-specific one; and there seem to be several approaches to it, but my application is analyzing Input.acceleration data to make tilt controls that don’t suck. Could someone who’s already got this stuff figured out point me to some example code on the interwebs of an elegant way to go about it?

How about taking the differential of the sequence? For each point, do something like

``````difference = Mathf.Sign(newVal - prevVal);
``````

When the sign changes from positive to negative, you’ve hit a peak. When it changes from negative to positive you’re at a valley. You can then save out and iterate through the points associated with each peak/valley, or just put them in a SortedList that will automatically sort them from the highest peak to lowest valley.