Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is swap() sometimes implemented by passing an array?

In some comp-sci papers and tests, I see swap() implemented like so:

void swap(int x, int y, int *a)
{
    int t = a[x];
    a[x] = a[y];
    a[y] = t;
}

Why not simply implement it like so:

void swap(int& x, int& y)
{
    int t = x;
    x = y;
    y = t;
}

Is the idea to the former to make the calling code cleaner, by not having to index into the array for the first two arguments? I realize it's not a very important question, since we should be using std::swap(), but I'm still curious.

like image 960
Fast Fish Avatar asked Nov 27 '10 21:11

Fast Fish


2 Answers

Not all programming languages support calling by reference. For instance, the latter way of doing swap doesn't apply to Java.

In books containing pseudo-code, usually there's a convention that arrays and pointers are not copied when passed and everything else is copied in a function call. The former way requires no special explanation about the way arguments are passed.

Regarding your final point about cleanliness, it's not so much different: in the former case, your call to swap would be simply: swap(i, j, a); whereas in the latter, you'll have to swap(a[i], a[j]);, introducing some brackets in the expression.

like image 71
mmx Avatar answered Nov 14 '22 22:11

mmx


Your second code sample is C++, NOT C. C++ supports reference parameters, but C only supports reference indirectly via pointers.

I agree that the second implementation is cleaner. In order to make it work in C, change the & in each of the parameters to * and dereference each x and y (also with *) inside the function.

like image 37
pr1268 Avatar answered Nov 14 '22 22:11

pr1268