简体   繁体   中英

Time complexity with Big O notation for a called function

I read many resources about calculating time complexity O(n) . I applied what I understand on my code.

Bellow is my code and my attempt to find time complexity .

my code:

    float Euclidean_distance(int array_point_A[20], int  array_point_B[20]) {
    float sum = 0.0;
    float  w[20] = { 0.0847282, 0.0408621, 0.105036, 0.0619821, 0.0595455, 0.0416739, 0.0181147, 0.00592921,
     0.040049, 0.0766054, 0.0441091, 0.0376111, 0.0124285, 0.0733558, 0.0587338, 0.0303001, 0.0579207, 0.0449221,
          0.0530462, 0.0530462 };

    for (int i = 0; i < 20; ++i) {
        float a = array_point_A[i] - array_point_B[i];
        float wieghted_distance = w[i] * (a * a); 
        sum += wieghted_distance;
    }
    return sqrt(sum);
}


int KNN_classifier(int X_train[4344][20], int Y_train[4344], int k, int data_point[20]) {

    // Calculate the distance between data_point and all points.    
    float array_dist[4344]{};
    int index_arr[4344]{} 
   for (int i = 0; i *< 4344; ++i) {
        array_dist[i] = Euclidean_distance(X_train[i], data_point);
        index_arr[i] = i;
    }

Now: for function Euclidean_distance it has 2 operations outside the loop and 3 operations inside the loop that will iterate 20 times . Thus, 2+3n then we have O(n) .

Now: for function KNN_classifier . it has a loop that will iterate 4344 times. Inside the loop , there is 2 operations . so we have 2n and then O(n) . // I am not sure about this solution.

This operation array_dist[i] = Euclidean_distance(X_train[i], data_point); confused me. So, do I need to include the Euclidean_distance time complexity in my calculation. If so, I guess the time complexity will be O(n^2) . But the two loops has different bounds.

Please I need help !!!

Big-O notation only has meaning relative to one or more parameters, but you haven't described which values in your code are variable and which are constants.

As it is written, the function KNN_classifier is actually O(1 ) because 4344 is a fixed constand and 20 is a constant. If 20 is a constant and the size of X_train and Y_train is meant to vary as some number n then it is O(n) . If the 20 constant also varies as m then it is O(n*m) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM