The reason is that you're not giving getAdd
a new value every iteration of the while
loop.
This means that the for
-loop inside the while
loop, this one:
for (int i =start; i < size; i++)
{
if(arr[i]<minEl)
{ minEl=arr[i];
getAdd=i;
}
}
if this loop doesn't find an element that is less than minEl
, which will happen in those occasions where arr[start]
is already the correct element, you will re-use the previous value given to getAdd
, and then swap the correctly placed element in arr[start]
with another previously correctly placed element in arr[getAdd]
, where getAdd < start
, messing up the sort order.
In the case where the first element is correctly placed, you will also probably use the uninitialized value for getAdd
, which depending on your compiler and compiler settings might be an arbitrary "random" value.
This had nothing to do with 6 items by the way. My guess is that you tested it with 6 items or less that didn't have this situation. Any sized array that had no elements in the right spot already would probably be sorted correctly.
To fix this, move the declaration of getAdd
into the while
loop, and give it a suitable value:
int start=0;
while(start<size)
{
int minEl = arr[start];
int getAdd = start;
for (int i =start; i < size; i++)
You can then also do a check before swapping:
if (start != getAdd)
swap( arr[start],arr[getAdd] );
With the change to getAdd
, you should find that your selection sort works as expected.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…