I'm trying to implement insertion sort using stl and vectors. I came up with this solution so far:
void insertionSort(vector<int> &v, int splitIndex);
int main() {
//vector<int> x = {55,33,99,11,22,44};
//vector<int> x = {55};
//vector<int> x = {55,11};
vector<int> x;
insertionSort(x, 0);
printVector(x);
return 0; }
void insertionSort(vector<int> &v, int splitIndex) {
vector<int>::iterator right = v.begin() + splitIndex + 1;
if(right == v.end())
return;
vector<int>::iterator left = v.begin() + splitIndex;
while(*right < *left && right != v.begin()) {
iter_swap(right, left);
right--;
left--;
}
insertionSort(v, splitIndex+1); }
It's working on all cases except for the empty vector case because the "right" pointer will be pointing outside the vector limit. I know it can be fixed by adding a condition on the beginning:
if(v.size() < 2) return;
But I don't like that tis condition will be executed for every recursion call.
Please advice. Thanks.