I have written a function that takes a vector of ints, and returns the minimum difference between two elements (ie, the difference of the elements that are nearest to one another).
I am trying to work out the algorithmic complexity. The first for loop iterates over all elements of the input (I'll call this N), which is linear complexity: O(n). The inner for loop iterates over N - 1 the first time, then N - 2, N - 3, ... N - N + 2, N - N + 1, 0. So I don't think this algorithm is O(n^2). My guess is it is O(N * log(N)), is that correct?
#include <cstdlib> #include <vector> long int function(const std::vector<int> &Input) { long int MinimumDifference = -1; for(size_t i = 0; i < Input.size(); i++) { for(size_t j = i + 1; j < Input.size(); j++) { long int Difference = abs(static_cast<long int>(Input[i] - Input[j])); if(Difference < MinimumDifference || MinimumDifference < 0) { MinimumDifference = Difference; } } } return MinimumDifference; } Edit: So the above is O(n^2), think I can achieve O(N * log(N)) by sorting the list first (using std::sort, which has O(N * log(N))), and then just iterate over the list to find the smallest difference.
#include <cstdlib> #include <vector> £include <algorithm> void function(const std::vector<int> &Input) { std::vector<int> SortedInput = Input; std::sort (SortedInput.begin(), SortedInput.end()); long int MinimumDifference = -1; for(size_t i = 0; i < SortedInput.size() - 1; i++) { long int Difference = abs(static_cast<long int>(SortedInput[i] - SortedInput[i + 1])); if(Difference < MinimumDifference || MinimumDifference < 0) { MinimumDifference = Difference; } } return MinimumDifference; }
O(n^2), this doesn't necessarily mean there are precisely n^2 operations to be performed. Rather, it stands forc * n^2, whereccan be any positive constant. In your case,c=1/2.