以下は、geeksforgeekからの最も近い対のポイントのコードスニペットです。2つの条件を持つループのbig O計算
コメントに見られるように、関数はO(n^2)ではなく線形で実行されると言います。
それは第二のループは、一定の時刻に実行することができるからである。ここでは
for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j)
は私の質問です:
このループのために、それは「しない限り、とにかくn回で実行されますj "は大きすぎません。
いくつかの "j"のループ内で実行されないことはわかっていますが、 でもループは "n"回実行されます。
したがって、大きなO表記を計算するときは、 内部ループを実行するケースのみを気にする必要がありますか?
もしそうなら、この問題について説明する良い参考資料をお勧めしますか?
// A utility function to find the distance beween the closest points of
// strip of given size. All points in strip[] are sorted accordint to
// y coordinate. They all have an upper bound on minimum distance as d.
// Note that this method seems to be a O(n^2) method, but it's a O(n)
// method as the inner loop runs at most 6 times
float stripClosest(Point strip[], int size, float d)
{
float min = d; // Initialize the minimum distance as d
qsort(strip, size, sizeof(Point), compareY);
// Pick all points one by one and try the next points till the difference
// between y coordinates is smaller than d.
// This is a proven fact that this loop runs at most 6 times
for (int i = 0; i < size; ++i)
for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j)
if (dist(strip[i],strip[j]) < min)
min = dist(strip[i], strip[j]);
return min;
}
http://www.geeksforgeeks.org/closest-pair-of-points/
平均的なケースでは、 'qsort'は' O(n log n) 'です。 – meowgoesthedog
@meowgoesthedog:私はそれがループを指していると仮定しましたが、あなたの読みが正しい可能性が高いです。 –
@ScottHunterよく、ポイントがソートされていない場合、forループ内のメソッドは正しくないので、無視することはできません。 – meowgoesthedog