Search code examples
c++sortingselection-sort

Selection sort in C++ (modified) not working for all cases


I was trying to modify the selection sort code in c++ to check the results. My modified code is:

#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 works for certain arrays but does not work for others. For example: If I enter 1,11,2,22,3 as the array, I get a proper output: 1,2,3,11,22. But, if I enter 1,11,2,22,3,33 as the array, I get the same array as the input as the output. Please tell me what is wrong with my code.


Solution

  • The issue is because of wrong place of the swap logic. The swap should be placed outside the inner loop.

    #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;
                }
            }
            //Swap here
            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;
    }
    

    Now this gives the output as expected.