After inserting 100000000 elements into my heap and unsorted list, it seems that the heap insertion is actually faster (12 seconds vs 20 seconds). Why is this? I believe heap insertion is O(logn) while unsorted list insertion is O(1). I also noticed that my heap insertion implementation doesn't actually scale with the number of inputs. This also confuses me.
Here is the code that I ran:
int main ()
{
clock_t unsortedStart;
clock_t heapStart;
double unsortedDuration;
double heapDuration;
int num_pushes = 100000000;
int interval = 10000;
ofstream unsorted ("unsorted.txt");
ofstream heap ("heap.txt");
UnsortedPQ<int> unsortedPQ;
HeapPQ<int> heapPQ;
unsortedStart = clock();
for (int i = 0; i < num_pushes; ++i)
{
if (i % interval == 0) {
unsortedDuration = ( clock() - unsortedStart ) / (double) CLOCKS_PER_SEC;
unsorted << unsortedDuration << " " << i << endl;
}
unsortedPQ.insertItem(rand() % 100);
}
heapStart = clock();
for (int i = 0; i < num_pushes; ++i)
{
if (i % interval == 0) {
heapDuration = ( clock() - heapStart ) / (double) CLOCKS_PER_SEC;
heap << heapDuration << " " << i << endl;
}
heapPQ.insertItem(rand() % 100);
}
return 0;
}
This is the heap implementation of insert (uses std::vector):
template <class T>
void HeapPQ<T>::insertItem(T data) {
//insert into back of heap (std::vector)
dataArray.push_back(data);
int i = dataArray.size() - 1;
//sifts the inserted element up
while (i != 0 && dataArray[(i - 1) / 2] > dataArray[i]) {
swap(dataArray[i], dataArray[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
This is the unsorted list implementation of insert (uses std::list):
//pushes element to the back of a std::list
template <class T>
void UnsortedPQ<T>::insertItem(T data) { dataList.push_back(data); }