对顺序搜索算法的测试

先利用之前一篇:《对产生不重复随机数组的算法测试》中的算法产生不重复随机数组,个数为1亿个元素

#include <algorithm> #include <time.h> #include <Windows.h> #include <iostream> using namespace std; typedef long long int _INT64; const unsigned len = 100000000; _INT64 arr[len] = {0}; void getRandArrayNoRepeat() { for (unsigned i=0; i<len; ++i) arr[i] = i; random_shuffle(arr, arr+len); } _INT64 ssearch1(_INT64 t) { for (unsigned i=0; i<len; ++i) { if (arr[i] == t) return i; } return -1; } _INT64 ssearch3(_INT64 t) { arr[len-1] = t; unsigned i; for (i=0; ; i+=8) { if (arr[i ] == t) { break; } if (arr[i+1] == t) { i+=1; break; } if (arr[i+2] == t) { i+=2; break; } if (arr[i+3] == t) { i+=3; break; } if (arr[i+4] == t) { i+=4; break; } if (arr[i+5] == t) { i+=5; break; } if (arr[i+6] == t) { i+=6; break; } if (arr[i+7] == t) { i+=7; break; } } if (i == len-1) return -1; else return i; } _INT64 ssearch2(_INT64 t) { _INT64 hold = arr[len-1]; arr[len-1] = t; unsigned i; for (i=0; ; ++i) { if (arr[i] == t) break; } arr[len-1] = hold; if (i == len-1) return -1; else return i; } int main() { getRandArrayNoRepeat(); //test1 DWORD stime = GetTickCount(); cout << "68204826 is in " << ssearch1(68204826) <<'/n';; DWORD test1 = GetTickCount(); cout << "ssearch1's running time = " << test1 - stime << " ms." <<'/n'; //test2 stime = GetTickCount(); cout << "68204826 is in " << ssearch2(68204826) <<'/n';; DWORD test2 = GetTickCount(); cout << "ssearch2's running time = " << test2 - stime << " ms." <<'/n'; //test3 stime = GetTickCount(); cout << "68204826 is in " << ssearch3(68204826) <<'/n';; DWORD test3 = GetTickCount(); cout << "ssearch3's running time = " << test3 - stime << " ms." <<'/n'; return 0; } 

 

测试运行结果:

68204826 is in 94856064

ssearch1's running time = 313 ms.


68204826 is in 94856064

ssearch2's running time = 328 ms.

加速5%

68204826 is in 94856064

ssearch3's running time = 234 ms.

加速10-20%

 

 

你可能感兴趣的:(算法,测试)