简体   繁体   中英

I made a function for selection sort, and I can't figure out what's going wrong here

I made a function for selection sort, and I can't figure out what's going wrong here.

void selection_sort(int n,int *arr){
    for(int i=0;i<n-1;i++){
        for(int j=i+1;j<n;j++){
  
            if(arr[j]<arr[i]){
                int temp=i;
                arr[i]=arr[j];
                arr[j]=arr[temp];
                
            }
        }
    }
}

In your selection_sort() function:

if(arr[j]<arr[i]){
    int temp=i;
    arr[i]=arr[j];
    arr[j]=arr[temp];
}

arr[temp] is arr[i] , and since you assign arr[i] with the value of arr[j] , arr[j]=arr[temp] is just arr[j] = arr[j] So this code just assigning arr[i] with the value of arr[j] .

Use std::swap() :

if(arr[j]<arr[i]){
    std::swap(arr[j], arr[j]);
}

Also, the logic appears to be bubble sort, not selection sort.

You have to save the value of actual iterate element in temp varaible. What you are actual do, is save actual iteration number-1 in temp variable.

void selection_sort(int n,int *arr){
    for(int i=0;i<n-1;i++){
        for(int j=i+1;j<n;j++){
            if(arr[j]<arr[i]){
                int temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }
}
void selection_sort(int n,int *arr){
int min_ix;  //minimum element index
for(int i=0;i<n-1;i++)  {
    min_ix = i;
    for(int j=i+1;j<n;j++){
          if(arr[j]<arr[min_ix]){
            min_ix = j;
            swap(arr[min_ix],arr[i]);          
         }
      }
   }
}

The code snippet use had provided was for bubble sort and this one's for selection sort.

selection sort: repeatedly finds the minimum element to sort an array bubble sort: repeatedly swaps the adjacent elements if they are in wrong order.

I always find a picture to help. Here's a good graphic I created some time ago:

选择排序动画

This is what your code should be doing.

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