1

The function:

double sum1(std::vector& v)
{    
    if (v.empty()) {
        return 0.0;
    }
    for(size_t i = 0; i < v.size() - 1; ++i) {
        std::sort(v.begin()+i, v.end());
        v[i+1] += v[i];
    }
    return v.back();
}

There are n-1 sorts each one shorter by 1, so time taken by the function for n elements will be:

T(n) = C*n + n*log(n) + (n-1)*log(n-1) + ... + 2*log(2) + 1*log(1)

How to solve this polynomial? Or I missed something?

midenok
  • 113
  • 2

2 Answers2

2

How to solve the polynomial: Clearly it's less than n * n * log (n) = O (n^2 log n). And clearly it is more than (n/2) * (n/2) * log (n/2) = O (n^2 log n). So it's n^2 log n.

However, your assumption that the sort is O (n log n) is not justified. Each time except the first you are sorting an array that is already sorted with the exception of the first array element. Many sort implementations will sort that kind of array in O (n), so the total time may be just O (n^2).

gnasher729
  • 32,238
  • 36
  • 56
2

Standard c++ std::sort implements quicksort algorithm, switching to mergesort if recursion is too deep.


Quicksort algorithm takes $\Omega(n*log(n))$ time in the best case, so you could assume repeating it $O(n)$ times will give a $O(n^2*log(n)$ time.

The thing which just might break our lower bound is the structure of your algorithm. If quicksort takes the last/first element (new element added to sorting on each iteration) it will break into sorting the sorted array on 1st recursive subcall, invoking its worst case performance of $O(n^2)$. This will bring your algorithms complexity up to $O(n^3)$.

Note that this fault is valid only if quicksort does always use first/last pivot. If randomization is doing the work of selecting a pivot, the runtime in the average and best case is $O(n^2*log(n))$, and $O(n^3)$ in worst case (rare).


Let us assume that your std::sort uses insertion sort. Insertion sort performs best on already sorted algorithms, and just needs to insert the last element added into its place in $O(n)$. This would make the whole algorithm run in $O(n^2)$.


This example is a perfect explanation of why it is imporant to learn underlaying aspects of sorting algorithms before relying on particular boxed function.

Petar Mihalj
  • 148
  • 1
  • 8