I have to implement insertion sort for an assignment, and I have an algorithm that aught to work (as far as I can tell), but is giving me trouble. I should also mention that we're using a template class in the assignment, though I doubt that would make a difference. First, here's the code:
vector<T>::size_type startIndex, minIndex, position;
for(startIndex=1; startIndex < v.size(); startIndex++)
minIndex = startIndex-1;
temp = v.at(startIndex);
while((minIndex >= 0) && (temp < v.at(minIndex)))
v.at(minIndex+1) = v.at(minIndex);
v.at(minIndex+1) = temp;
The problem is that, if I leave the first comparison in the while loop condition as
minIndex >= 0
, I get a runtime error and the program crashes. But as far as I can see, that's the way it should be.
If I change the condition to
]minIndex > 0
, I no longer have a run time error, and the sorting works properly EXCEPT that the first value in the vector is skipped.
I can't see why that condition should be giving me an error. I also can't see another way to make the code work properly.
If anyone can see anything I might be missing, I'll greatly appreciate it. :)