#include <stdio.h>
// There is no need to allocate the third position for temp
void reverse_array(int a[], int cnt)
{
int first, last;
for (first=0, last=cnt-1; first<last; first++, last--)
{
inplace_swap(&a[first], &a[last]);
}
}
int main()
{
int a[5] = {1,2,3,4,5};
reverse_array(a, 5);
for (int i=0; i<5; i++)
{
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
這裏的交換數據採用了布爾代數中的布爾環,如果採用
void inplace_swap(int *x, int *y)
{
int itmp = *x;
*x = *y;
*y = itmp;
}
雖然性能上並沒有損失,卻浪費了空間,無論是通過int數值交換還是利用臨時指針進行交換。如果是對struct進行交換,那麼最好的方法無疑就是
void inplace_swap(int *x, int *y)
{
int *ptmp = x;
x = y;
y = ptmp;
}