temporary
temporary

Reputation: 1

selection sort is not working properly it is not scanning the number which are at last of the array

#include<iostream>
using namespace std;
 
int main()
{
    int arr[] = {40,20,14,20,55,14,22,45,22,447,441,224,421,2,14,1,9};
    int size = sizeof(arr) / sizeof(int);

    for (int i = 0; i < size; i++)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;

    for (int i = 0; i < size; i++)
    {
        int Index_of_Min = i;

        for (int j = i+1; j < size; j++)
        {
            if (arr[j] < arr[Index_of_Min])
            {
                Index_of_Min = j;
            }
            swap(arr[Index_of_Min], arr[i] );
        }      
    }
    
    for (int i = 0; i < size; i++)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
    
return 0;
} 

in the above program when we run it the number 9, 224 are not getting sorted

i want to understand why the program is not working anyone who knows the solution then your help is much appreciated and please explain me what was my mistake so i will not repeat it again. Thank You

Upvotes: -1

Views: 22

Answers (1)

john
john

Reputation: 87997

Saw the exact same error only a few days ago. Your loop is wrong, specifically the swap is in the wrong place. This is how it should look

for (int i = 0; i < size; i++)
{
    int Index_of_Min = i;

    for (int j = i+1; j < size; j++)
    {
        if (arr[j] < arr[Index_of_Min])
        {
            Index_of_Min = j;
        }
    }      
    swap(arr[Index_of_Min], arr[i] );
}

You do the swap after the inner loop has found the index of the minimum element, not while it is finding that index.

Upvotes: 1

Related Questions