There are a number of factors involved here.
First, the mistake is in passing begin+1 and pos+1 for the recursive call of selection_sort. By adding 1 to begin, you effectively lose elements, since by adding 1 to the pos, for example, in the second iteration, you will be taking the index 1 of a vector that has already been incremented, so you are taking the element 2.
Fixing your code would look like this (already adapting the new stop condition):
template <typename T> void selection_sort(T* begin, T* end, unsigned pos = 0)
{
if(pos < ((end - begin) - 1))
{
for(int i = pos+1; i < (end - begin); i++)
{
if(begin[pos] > begin[i]) swap(begin[pos], begin[i]);
}
selection_sort(begin, end, pos+1);
}
else return;
}
However, although it works, there are a few more things that could be arranged here:
- the
else return; is useless
- Selection Sort could be done without recursion, by the way, it would spend less memory doing with two
for, instead of with recursion
- using the subtraction result of the vectors to obtain an integer (in your case, the vector size) is not very advisable... I would replace the parameter
T* end for int count, since end is not used for anything, whether or not
- the parameter
unsigned pos should be replaced by int pos, to make the type match (you are using int for i, but unsigned for pos)
To illustrate how you would look with these changes that I suggested:
template <typename T> void selection_sort(T* begin, int count)
{
for (int pos = 0; pos < count - 1; pos++)
{
for (int i = pos+1; i < count; i++)
{
if (begin[pos] > begin[i]) swap(begin[pos], begin[i]);
}
}
}
Thanks; I can’t use Std::swap because I can’t at least include <Algorithm>
– user2692
I get it. In this case, okay.
– Lucas Lima
It is worth mentioning in the text of the answer, that in addition to having altered the initialization of the
i, exchangingpos+1forpos, the parameterpos+1recursive call was also changed topos. In fact, let the variable initializeiaspos+1is better, since you already skips an unnecessary comparison (ifiis equal topos, then comparebegin[pos]withbegin[i]is redundant). Yet, as the value ofposis not changed between recursive calls, will always remain0, it wouldn’t even need to be passed as a parameter.– carlosrafaelgn
Actually, the
poswas unused anyway. I edited. Thanks!– Lucas Lima