Search code examples
c++dev-c++

Why this Selection sort code in Cpp, not giving required Output


#include<iostream>

using namespace std;
int min_arr(int arr[],int size);
void swap(int *,int *);
int main()
{
    int arr[10]={31,2,55,3,77,12,89,98,43,34},loc;
    int* arr1;
    arr1 = &arr[0];
    for(int i=0;i<10;i++)
    {
        for( int j=i;j<9;j++)
        {
            loc = min_arr(arr1,(10-i));
            swap(&arr[loc],&arr[i]);
            arr1++;
        }
    }   

    for(int i =0; i<10;i++)
        cout<<arr[i]<<endl;

    return 0;
}

int min_arr(int arr[],int size)
{
    int k=0;
    int temp=arr[0];
    for(int i=1;i<size;i++)
    {
        if(arr[i]<temp)
        {
            temp=arr[i];
            k=i;
        }   
    }

    return k;
}

void swap(int *a, int *b)
{
   int temp;
   temp=*a;
   *a=*b;
   *b=temp;
}  

Why this Selection sort code in Cpp, not giving required Output? Kindly find the flaw! I have taken two functions to find min of the sub arrays as we procede. And as i find the min, i return its index and swap the first position of the sub array and minimum valued element!


Solution

  • After rearranging the code and adding some debug lines, it's pretty easy to find out what's wrong:

    • Firstly, the second loop (j loop) is completely pointless
    • Secondly loc variable is not 0-based but i-based (as you searched over arr1, which is incremented by the loop), so arr[loc] should be arr[loc+i]

    Corrected, smartly indented (that's important to make tour code easily readable) code:

    #include<iostream>
    
    #define ARRAY_SIZE 10
    using namespace std;
    int min_arr(int arr[],int size);
    void swap(int *,int *);
    int main()
    {
        int arr[ARRAY_SIZE]={31,2,55,3,77,12,89,98,43,34},loc;
        int* arr1;
        arr1 = &arr[0];
        for( int i = 0; i < ARRAY_SIZE; i++ )
        {
            //for( int j = i; j<ARRAY_SIZE-1; j++ )
            {
                loc = min_arr(arr1,(ARRAY_SIZE-i));
                // for debug:
                //std::cout << "min found at " << loc << std::endl;
                swap(&arr[loc+i],&arr[i]);
    
                // for debug:
                //for( int i =0; i<ARRAY_SIZE; i++ )
                //  cout << arr[i] << " ";
                //cout << std::endl;
    
                arr1++;
            }
        }   
    
        for( int i =0; i<ARRAY_SIZE; i++ )
            cout<<arr[i]<<endl;
    
        return 0;
    }
    
    int min_arr( int arr[], int size )
    {
        int k=0;
        int temp=arr[0];
        for( int i=1; i<size; i++ )
        {
            if( arr[i] < temp )
            {
                temp=arr[i];
                k=i;
            }   
        }
        return k;
    }
    
    void swap(int *a, int *b)
    {
        int temp;
        temp=*a;
        *a=*b;
        *b=temp;
    }  
    

    It will output:

    2
    3
    12
    31
    34
    43
    55
    77
    89
    98