简体   繁体   中英

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

Your specific problem with min_element is

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

it take the value of the iterated to element instead of a reference/iterator to it, try instead to do

for(int i=0;i<n-1;i++){
    auto Min=min_element(arr+i,arr+n); // iterator
    Swap(arr[i],*Min);
}

You will now find our that your Swap is also not working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM