I'm working with a time series (of numbers, e.g., temperatures, stock prices, etc.) where I want to maintain a sorted moving window of N elements (N generally < 200).

In other words, I want to take Data 1 .. 100, sort it; then Data 2 .. 101, sort that; and so on down the line.

I figure once the array has been filled & sorted for the first time, there must be a relatively elegant & efficient solution for removing the oldest data point & inserting the newest one in the correct location.

One solution would be to simply replace the oldest data point with the new one, then do a bubble sort since that method is fairly efficient when data is mostly sorted. (Only one element will be out of position, though it may require multiple exchanges to fix.)

But it seems to me there must be an even better approach. It should be possible, for instance, to take advantage of the fact that for these particular time series, the newest data point will almost always have a value very close to the value of the previous data point that was added.

Since this code will be called very frequently, the most efficient algorithm will definitely help a lot. If it's relevant, I'm working in Visual Basic 6 for the moment.

Many thanks for any suggestions!