Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any idea how to transform this O(n^2) algo into a O(n)

I have the following algorithm which scan a large circular array (data). At certain point in the array, I need to take a look at the past values (0 = newest data point, n = oldest data point) and determine if there was a value 5% below the current value. I ended up writing a O(n^2) algorithm which works okay, but this doesn't scale.

        const int numberOfDataPointsInPast = 1000;
        int numberOfDataPoints = 0;
        for (int i = numberOfDataPointsInPast; i >= 0; i--)
        {
            double targetPoint = data[i] * 0.95;
            for (int j = i + numberOfDataPointsInPast; j > i; j--)
            {
                if (data[j] <= targetPoint)
                {
                    numberOfDataPoints++;
                    break;
                }
            }
        }

Any idea how I could transform this into a O(n) algo? Thanks!

like image 894
Martin Avatar asked Jun 22 '10 13:06

Martin


People also ask

What is complexity n2?

O(N²) — Quadratic O(N²) represents the complexity of an algorithm, whose performance is proportional to the square of the size of the input elements. It is generally quite slow: If the input array has 1 element it will do 1 operation, if it has 10 elements it will do 100 operations, and so on.

Which is better O N or O 1?

An algorithm that is O(1) with a constant factor of 10000000 will be significantly slower than an O(n) algorithm with a constant factor of 1 for n < 10000000.

Is an O N 2 algorithm better than O N algorithm?

Save this question. Show activity on this post. If n<100 then O(n2) is more efficient, but if n≥100 then O(nlogn) is more efficient.


1 Answers

While iterating the array store the lowest value. This requires to create a min variable and perform a compare check in every step. Instead of comparing all previous values with the new one, compare it only with the lowest.

like image 197
kgiannakakis Avatar answered Nov 07 '22 03:11

kgiannakakis