Home > Net >  Coufused about using cpp to achieve selection sort
Coufused about using cpp to achieve selection sort

Time:01-22

I tried to implement selection sorting in C ,when i encapsulate the swap function, the output shows a lot of zeros.But at beginning of array codes still work.When I replace swap function with the code in the comment, the output is correct. I am so confused by this result, who can help me to solve it.

#include <iostream>
#include <string>

using namespace std;

template<class T>
int length(T& arr)
{
    return sizeof(arr) / sizeof(arr[0]);
}

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


int main()
{
    int array[] = { 2,2,2,2,6,56,9,4,6,7,3,2,1,55,1 };
    
    int N = length(array);

    for (int i = 0; i < N; i  )
    {
        int min = i; // index of min
        for (int j = i   1;j < N; j  )
        {
            if (array[j] < array[min]) min = j;
        }

        swap(array[i],array[min]);

        // int temp = array[i];
        // array[i] = array[min];
        // array[min] = temp;
    }
    for (int i = 0; i < N; i  )
    {
        int showNum = array[i];
        cout << showNum << " ";
    }
    return 0;
}

CodePudding user response:

Your swap function is not doing what it is supposed to do. Just use this instead or fix your current swap.

void swap(int& a, int& b){
   int temp = a;
   a = b;
   b = temp;
}

CodePudding user response:

Problem is that your swap function do not work if a and b refer to same variable. When for example swap(array[i], array[i]) is called.

Note in such case, this lines: b = a - b; will set b to zero since a and b are same variable.

This happens when by a chance i array element is already in place.

offtopic:
Learn to split code into functions. Avoid putting lots of code in single function especially main. See example. This is more important the you think.

  •  Tags:  
  • Related