Selection sorting. not getting the required output

What is wrong with this code? Not getting the right output.

void selectionSort(vector<int>& arr, int n)
{   
       for(int i = 0; i < n-1; i++ )
       {   
           int min = arr[i];
           for(int j = i+1; j < n; j++)
           {
               if(arr[j] < min)
                   min = arr[j];
           }
           swap (min, arr[i]);
       }
}

>Solution :

You are using the local variable min in the swap where you needed to use the vector element.

swap(arr[index_min], arr[i]) // `index_min` is the index of the current min value.

Leave a Reply