Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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 ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question