Selection Sort Swap Function

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;
 }
closed account (o3hC5Di1)
Hi there,

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.

All the best,
NwN
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

using namespace std; // bad habit

swap(Array[i], Array[index_Largest]);


http://www.cplusplus.com/reference/algorithm/swap/
Thanks guys. It's always the small things that tend to elude my mind.
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.

void swap(int &a, int &b);
Last edited on
Topic archived. No new replies allowed.