I keep looking back at my swap function inside my Selection Sort Function and I keep thinking that it's not right. I'm not sure why but I feel that I'm doing it wrong. Advice is appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Called inside my selection_Sort()
swap(Array[i], Array[index_Largest]);
// Swap Declaration in my header
swap(int, int);
// Swap Definition in my class
swap(int a, int b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}
You're swapping elements of an array - so a and b should be positions in the array and you should pass in the array too:
1 2 3 4 5 6 7 8 9 10 11 12 13
// Called inside my selection_Sort()
swap(Array[i], Array[index_Largest], Array);
// Swap Declaration in my header
swap(int, int, int[]);
// Swap Definition in my class
swap(int a, int b, int arr[])
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
Hope that makes sense. Please do let us know if you have any further questions.
The idea itself is good, but the function doesn't work because parameters a and b are passed by value.
This means that a and b are copied inside your swap() function as if they are local variables. For example temp is a local variable. So any way you change a and b does not affect the "real" variables that you want to swap.
How to fix this?
Method A: Do not pass by value, pass by reference instead.
1 2 3 4 5 6 7 8 9 10
swap(int &, int &);
// the code inside remains the same, because it is correct
swap(int &a, int &b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}
Method B: You are reinventing the wheel by creating your own swap() function. C++ already has one in the algorithm library.
1 2 3 4 5 6 7 8 9 10 11
#include <algorithm>
// ...
std::swap(Array[i], Array[index_Largest]);
// or
usingnamespace std; // bad habit
swap(Array[i], Array[index_Largest]);
It's always the small things that tend to elude my mind.
It's the same for pretty much everybody, with this thread being a perfect example.
Both I and NwN missed that your swap() function didn't have a return type.