Running time of sort help.
Nov 29, 2012 at 6:15am UTC
I wrote a test that creates different sized vectors of random integers and displays the number of times the inner loop runs for each array. However it displays the wrong number. Ex. if I input 10, it should output 78. Any idea what's the problem? Some suggestions would be nice.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
#include <cassert>
#include <vector>
#include <cstdlib>
using namespace std;
long sort(vector<int > & v)
{
long innerLoopCount = 0;
for (int i = 0; i < v.size(); ++i)
{
int k = i;
for (int j = i + 1; j < v.size(); ++j)
{
if (innerLoopCount = k + j);
}
}
return innerLoopCount;
}
int main()
{
srand(time(0));
vector<int > v(10);
for (int i = 0; i < 10; ++i)
{
v.push_back(rand());
}
cout << sort(v);
}
Nov 29, 2012 at 7:10am UTC
I think this is what you meant to write:
1 2 3 4 5 6 7 8 9 10 11 12
long sort(int n)
{
long innerLoopCount = 0;
for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
innerLoopCount++;
}
}
return innerLoopCount;
}
By the way, it can be proven that for all n >= 0, sort(n) == (n*n-n)/2.
Topic archived. No new replies allowed.