mercredi 25 novembre 2020

Strange Output in Selection Sort using C++ min_element()?

I have implemented this code myself for Selection Sort after understanding the logic. You can clearly see I have used C++ STL's min_element() to find the minimum element in the array. But the Output is Completely Wrong. It seems as if the forward iterator first for min_element() is not iterating. Can someone help me finding the underlying problem. Thanks in Advance !

#include<iostream>
#include<algorithm>


using namespace std;

void Swap(int &a,int &b){
    a=a+b;
    b=a-b;
    a=a-b;
}


void SelectionSort(int arr[],int n){
    int Min;
   
    for(int i=0;i<n-1;i++){

        Min=*min_element(arr+i,arr+n);
      
        Swap(arr[i],Min);
        
       
    }
    for(int i=0;i<n;i++){
        cout<<arr[i]<<" ";
    }
    
}

int main(){
    int arr[]={64, 25, 12, 22, 11};
    int n=sizeof(arr)/sizeof(arr[0]);
    SelectionSort(arr,n);
    return 0;
}

OUTPUT :

11 11 11 11 11

Aucun commentaire:

Enregistrer un commentaire