I have to add: I call my linear search 15,000 times, and the lowest range that I look up is up to 50,000 with each iteration. Thus, at the first iteration, there are 15,000 * 50,000 requests. This should take more than 0 ms.
I have this basic Linear search:
bool linearSearch(std::vector<int>&primes, int number, int range) {
for (int i = 0; i < range; i++) {
if (primes[i] == number)
return true;
}
return false;
}
I use time:
void timeLinearSearch(std::vector<int>& primes) {
clock_t start, stop;
size_t NRND = 15000;
for (int N = 50000; N <= 500000; N += 50000)
{
for (int repeat = 0; repeat < 5; repeat++) {
start = clock();
for (int j = 0; j < NRND; j++) {
linearSearch(primes, rand(), N);
}
stop = clock();
std::cout << stop - start << ", " << N << std::endl;
}
}
}
The problem is that the time is 0 ms. The primes vector has approximately 600,000 elements in it, so the search remains within the range.
In a linear search, if I change:
if(primes[i] == number)
at
if(primes.at(i) == number)
then I get the time> 0 taken for the search.
I compared my linear search with primes.at (i) with std :: find ():
for (int j = 0; j < NRND; j++) {
std::find(primes.begin(), primes.begin() + N, rand());
}
and it is about 200 ms faster than my .at () find.
Why does my search with std :: vector [i] give me 0ms time?