Search code examples
c++sortingselection-sort

Selection Sorting in C++ not working correctly


I was doing selection sort, it is running completely but the results are not correct.

This is my code:

#include<iostream> 
using namespace std; 

int main() 
{ 
  int array[5], temp, min, i, j; 
  for(i = 0; i <= 4; i++) 
  { 
    cout << "Enter the value"<<endl; 
    cin >> array[i]; 
  } 
  cout << "Values before sorting:" << endl; 
  for(i = 0; i <= 4; i++) 
    cout << array[i] << " "; 

  cout << endl; 
  for(i = 0; i <= 4; i++) 
  { 
    min = i; 
    for(j = i + 1; j <= 4; j++) 
    { 
      if(array[j] < array[min]) 
        min = j; 

      if(min != i) 
      { 
        temp = array[j]; 
        array[j] = array[j + 1]; 
        array[j + 1] = temp; 
      } 
    } 
    cout << "values after sorting" << endl; 
    for(i = 0; i <= 4; i++) 
      cout << array[i] << " ";  
  } 
} 

can anyone tell me whats the error in my code


Solution

  • The error is in the way you update the array after finding the minimum. In each iteration, you should find the minimum value between array[i]..array[4], and then you need to swap array[i] with array[min] as follows:

    #include<iostream> 
    using namespace std; 
    int main() { 
        int array[5],temp,min,i,j; 
        for(i=0;i<=4;i++) 
        { 
            cout<<"Enter the value"<<endl; 
            cin>>array[i]; 
        } 
        cout<<"values before sorting"<<endl; 
        for(i=0;i<=4;i++) 
        { 
            cout<<array[i]<<" "; 
        } 
        cout<<endl; 
        for (i = 0; i <= 4; i++)
        {
            min = i;
            for (j = i + 1; j <= 4; j++)
            {
                if (array[j] < array[min])
                {
                    min = j;
                }
            }
            if (min != i)
            {
                temp = array[i];
                array[i] = array[min];
                array[min] = temp;
            }
        }
        cout << "values after sorting" << endl;
        for (i = 0; i <= 4; i++)
        {
            cout << array[i] << " ";
        }
    }