Search code examples
c++sortingselection-sort

Selection Sort C++ Wrong Output for one element?


For the following implementation of Insertion Sort when i used random function to generate an arbitrary input, it gave wrong output since one element appears wrongly placed as Highlighted in Picture. I tried hard to understand whereas is the mistake, but couldn't figure it out. What is Wrong in my Code ?

enter image description here

#include<iostream>
#include<cstdlib>
using namespace std;

template <class Item>
void exch(Item &A, Item &B)
{
    Item t = A ; 
    A = B; 
    B = t; 
}

template<class Item>
void selection(Item list[],int last)
{
    Item holdData;
    int smallest,current,walker;

    for(current=0;current<=last;current++)
    {
        smallest = current;
        for(walker=current+1;walker<=last;walker++)
        {
            if(list[walker] < list[smallest])
                smallest = walker;

            //smallest selected, exhange with the current
            exch(list[smallest],list[current]);
        }
    }
}

int main()
{
    int N = 20;
    int *a = new int[N];
    for(int i=0;i<N;i++) a[i] = 1000*(1.0*rand()/RAND_MAX);

    cout<<"Before sorting : \n";
    for(int i=0;i<N;i++)
        cout<<a[i]<<" ";

    selection(a,N-1);

    cout<<"\n\nAfter Sorting : \n";
    for(int i=0;i<N;i++)
        cout<<a[i]<<" ";

    cout<<endl;
    return 0;
}

Solution

  • smallest = current;
    for(walker=current+1;walker<=last;walker++)
    {
        if(list[walker] < list[smallest])
            smallest = walker;
    
        //smallest selected, exhange with the current
        exch(list[smallest],list[current]);
    }
    

    Here smallest isn't actually selected yet, put it outside the loop:

    smallest = current;
    for(walker=current+1;walker<=last;walker++)
    {
        if(list[walker] < list[smallest])
            smallest = walker;
    }
    //smallest selected, exhange with the current
    exch(list[smallest],list[current]);