所以我創建了一些隨機整數並將它們放入一個列表中。我做了一個副本,然後我排序了原始列表。當我通過排序列表搜索特定項目時,它比我在未排序副本中的速度慢得多。爲什麼會發生?這是我使用的代碼和最後的一些運行時。排序列表與未排序列表的線性搜索 - 爲什麼排序較慢?
int main(){
const int SIZE = 100000, MAX_ELM = 10000000;
list<int> sortedList;
list<int> unsortedList;
int indexToFind, itemToFind;
srand(time_seed());
indexToFind = SIZE/2;
//initialize list
for (int i = 0; i < SIZE; i++){
if (i == indexToFind){
itemToFind = randomNum(0, MAX_ELM);
sortedList.push_back(itemToFind);
}
else
sortedList.push_back(randomNum(0, MAX_ELM));
}
unsortedList = sortedList; //copy ctr
sortedList.sort();
clock_t start, end;
int sortedItemIndex = 0;
//search for item in sorted list
start = clock();
list<int>::iterator it;
for (it = sortedList.begin(); it != sortedList.end(); ++it){
if ((*it) == itemToFind){
break;
}
sortedItemIndex++;
}
end = clock();
cout << "index: " << sortedItemIndex << " item: " << itemToFind << endl;
cout << (double)(end - start)/(double)CLOCKS_PER_SEC << endl << endl;
//unsorted
start = clock();
for (it = unsortedList.begin(); it != unsortedList.end(); ++it){
if ((*it) == itemToFind)
break;
}
end = clock();
cout << "index: " << indexToFind << " item: " << itemToFind << endl;
cout << (double)(end - start)/(double)CLOCKS_PER_SEC << endl;
}
這裏是我播種蘭特()函數,但我不認爲他們是重要的
int randomNum(int min, int max){
return rand() * (1.0/(RAND_MAX + 1.0)) * (max - min);
}
unsigned time_seed(){ // implementation from online
time_t now = time(NULL);
unsigned char *p = (unsigned char *)&now;
unsigned seed = 0;
size_t i;
for (i = 0; i < sizeof now; i++)
seed = seed * (UCHAR_MAX + 2U) + p[i];
return seed;
}
我的運行時間是:
排序列表 - 指數:44315項: 4439392時間:0.047秒
無序 - 指數:50000項:4439392時間:0.028秒
您是否在使用渦輪增壓的機器上進行測試? – James
您是否正在測試版本配置?我[無法複製](http://coliru.stacked-crooked.com/a/db28de3a8bd59904)你的問題。你也總是得到這樣的結果? –
@詹姆斯號我正在使用2 GHz和6GB RAM的i7 – kamoussa