I was attempting to tweak the selection sort code in C++ in order to test the results.
My updated code is as follows:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter number of elements\n";
cin>>n;
int i,j,small,pos,t;
int a[n];
cout<<"Enter elements of array\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n-1;i++)
{
small=a[i];
pos=i;
for(j=i+1;j<n;j++)
{
if(a[j]<small)
{
small=a[j];
pos=j;
}
t=a[i];
a[i]=a[pos];
a[pos]=t;
}
}
cout<<"Sorted array:\n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
This code is valid for certain arrays but not for others.
As an example:
When I input 1,11,2,22,3 as the array, I receive the correct result: 1,2,3,11,22.
However, if I enter the array as 1,11,2,22,3,33, I receive the same array as the input as the result.
Please let me know what's wrong with my code.