void swap( int x, int y ) { int temp ; temp = x ; x = y ; y = temp ; }we'd have a problem. We would indeed swap the values of
x
and y
, but they
are only local copies of the numbers.
If we call swap()
with a command like:
swap( a[i], a[j] ) ;then the values of
a[i]
and a[j]
won't be changed.
However, we can write swap()
using pointers.
Consider the function:
void swap( int *x, int *y ) { int temp ; temp = *x ; *x = *y ; *y = temp ; }Here we're not swapping the values of
x
and y
.
They are pointers to the actual numbers we want to swap, so we swap
the integers that they point to.
That also means that we call it differently; we would call
swap()
with a statement like:
swap( &a[i], &a[j] ) ;This figure shows the situation before calling
swap()
,
and this figure shows the situation at the end of swap()
.
Proceed to the next part.