#include <stdlib.h>
#include <time.h>
#include <iostream>
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
struct Node{
int item;
Node* next;
};
double diffclock(clock_t clock1, clock_t clock2){
double diffticks = clock1 - clock2;
double diffms = (diffticks * 1000) / CLOCKS_PER_SEC;
return diffms;
}
int getEntry(int index, int* array){
return array[index];
}
int getEntry(int index, Node* head){
Node* curr = head;
for( int i = 0; i < index && curr != NULL; i++){
curr = curr->next;
}
return (curr->item);
}
#define NUM_REPETITIONS 500
int main(int argc, char* argv[]){
clock_t begin, end;
srand (time(NULL));
int* randomQueries = new int[NUM_REPETITIONS];
int maxN = -1;
do{
cout << "Enter the maximum value of N: ";
cin >> maxN;
}while( ! cin );
cerr << "n\tArray\tLinked List\n";
for(int n = 10; n <= maxN; n *= 10){
cerr << n;
int* array = new int[n];
for( int i = 0; i < n; i++){
array[i] = i;
}
Node* head = new Node;
Node* curr = head;
int i = 0;
curr->item = array[i];
for( i = 1; i < n; i++){
curr->next = new Node;
curr = curr->next;
curr->item = array[i];
}
curr->next = NULL;
for( int j = 0; j < NUM_REPETITIONS; j++){
randomQueries[j] = rand() % n;
}
begin = clock();
for( int j = 0; j < NUM_REPETITIONS; j++){
getEntry( randomQueries[j], array);
}
end = clock();
cerr << '\t' << diffclock( end, begin);
begin = clock();
for( int j = 0; j < NUM_REPETITIONS; j++){
getEntry( randomQueries[j], head);
}
end = clock();
cerr << '\t' << diffclock( end, begin);
cerr << '\n';
delete[] array;
}
return 0;
}