Home > Back-end >  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

Time:01-13

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];
                
            }
        }
    }
}

CodePudding user response:

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.

CodePudding user response:

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;
            }
        }
    }
}

CodePudding user response:

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.

CodePudding user response:

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

Selection Sort Animation

This is what your code should be doing.

  •  Tags:  
  • Related