If the input array is empty, then array.size()
should be 0. The first for
, that goes from 0
to array.size() - 1
, should mean it goes from 0
to -1
, right?
This for
then, should not be entered and the function should return the inversionsCounter value which would be 0
But this doesn't happen, and the code enters an infinite loop. Why is this?
Here is the code:
#include <vector>
#include <iostream>
using namespace std;
int countInversions(vector<int> array)
{
int inversionsCounter = 0;
for (int i = 0; i < array.size() - 1; ++i)
for (int j = i + 1; j < array.size(); ++j)
if (array[i] > array[j])
++inversionsCounter;
return inversionsCounter;
}
int main()
{
vector<int> array = {};
cout << array.size();
cout << countInversions(array);
}