Last active
October 13, 2015 09:58
-
-
Save sirupsen/4178574 to your computer and use it in GitHub Desktop.
Implementation of a faster linear search, by sparing a single comparison.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
using namespace std; | |
int main() | |
{ | |
int sought = 4e8; | |
vector<int> vec; | |
for(size_t i = 0; i < sought + 20; i++) | |
vec.push_back(i); | |
size_t i = 0; | |
// first: 3.5s | |
for(;i < vec.size(); i++) | |
if(vec[i] == sought) break; | |
// second: 3.8s | |
while(true) { | |
if(vec[i] == sought) { | |
break; | |
} else { | |
i++; | |
if(i >= vec.size()) { | |
break; | |
} | |
} | |
} | |
// 3.1s | |
i = 0; | |
vec.push_back(sought); | |
while(true) { | |
if(vec[i] == sought) { | |
if (i < vec.size()) break; // success | |
else if(i == vec.size()) break; // not success | |
} else { | |
i++; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment