C
C
Chekistchek2018-10-01 20:29:53
C++ / C#
Chekistchek, 2018-10-01 20:29:53

Which algorithm is more efficient?

Need to find the sum of the elements between the first and second positive elements, I did it in two ways. Which is more efficient? (The array can be any length, I took 8 elements)

int arr[] = {1,-5,-6,3,-85, -4, -9,-7};
    int interval_sum = 0;
    bool is_has_len = false;
    
    int i = 0;
    while(arr[i++]<=0 && i < 8); // находим номер первого отрицательного после положительного
    
    while(arr[i]<=0 && i < 8) { // суммируем
        interval_sum += arr[i++];
        is_has_len = true;
    }

    if (!is_has_len) {
        cout << "interval is null, we can not count a sum" << endl;
    } else if (i == 8) {
        cout << "Less than two 'plus' numbers, we can not count a sum" << endl; 
    } else {
        cout << "sum is " << interval_sum << endl;
    }

int arr[] = {-1,-5,-6,3,-85, 4, 9,7};
    int interval_sum = 0;
    bool is_count = false;
    bool is_was_interval = false;
    bool is_has_len = false;
    
    for (int i = 0; i < 8; i++){
        /* подсчет суммы элементов между первыми двумя положительными*/
        if (!is_was_interval) {// если еще не было интервала
            if (arr[i]>0 && is_count){ //если мы уже считаем и нам попалось положительное, то останавливаем счет
                is_was_interval = true;
            } else {
            
                if (is_count) {
                    interval_sum += arr[i];
                    is_has_len = true;
                }
               
                if (arr[i]>0 && !is_count){// если положительное и не считали, то начинаем
                    is_count = true;
                }
            }
        }
    }

    
    if (!is_has_len) {
        cout << "interval is null, we can not count a sum" << endl;
    } else if (!is_was_interval) {
        cout << "Less than two 'plus' numbers, we can not count a sum" << endl; 
    } else {
        cout << "sum is " << interval_sum << endl;
    }

At first glance, the first algorithm is more efficient due to the smaller "volume", but there is a double iteration of the array.
I would be grateful if you suggest a better solution.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
xmoonlight, 2018-10-01
@xmoonlight

Option 1 and there is a single incomplete (in most cases) array iteration.
In the 2nd option - enumeration with checks, which will be much slower ...

L
Leevz, 2018-10-01
@Leevz

Run both in succession and determine the best one by time

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question