The function works fine if the "small" I have chosen, ie, a[i], is *not* the smallest element in the array. It swaps and sorts just fine. But when the "small", ie, a[i], is the smallest element in the array already, then it goes bonkers, still substituting it with the previous value of "pos".
How do I remedy this?
Here is the code I have written -
How do I remedy this?
Here is the code I have written -
Code:
void selection(int a[], int size)
{
int small, pos=0, temp, flag=0;
for(i=0;i<(size-1);i++)
{
small=a[i];
for(j=i+1;j<size;j++)
{
if(a[j]<small)
{
flag=1;
small=a[j];
pos=j;
}
else flag=0;
}
if(flag=1)
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
cout<<"\nArray after Pass "<<i+1<<" is - ";
for(int k=0;k<size;k++)
cout<<a[k]<<" ";
}
cout<<"\n\nThe finished and sorted array is as follows...\n\n";
display(a,size);
return;
}
Comment