在线编译器 C

#include <stdio.h> void swap(int *x,int *y) { *x^=*y; *y^=*x; *x^=*y; return ; } void swap_min_max(int *a, int n) { int mx=a[0],nmx=0,mi=a[0],nmi=0; for(int i=1;i<n;i++) { if(*(a+i)>mx){ mx=*(a+i);nmx=i; } if(*(a+i)<mi){ mi=*(a+i);nmi=i; } } swap(a+nmx,a+nmi); return ; } int main() { int a[10]={0,-2,2,2,0}; swap_min_max(a,5); for(int i=0;i<5;i++) printf("%d ",a[i]); return 0; }
This code finds the minimum and maximum values in an array and swaps their positions. It uses a XOR-based swap function and pointer arithmetic to access array elements. The main function tests it with a small array.

- The XOR swap technique can fail when both pointers point to the same memory location. Consider what happens if the minimum and maximum are at the same index, or if the array has only one element.
- The initial values for `mx` and `mi` are both set to `a[0]`, but the indices `nmx` and `nmi` both start at 0. If the first element is both the minimum and maximum, the swap will try to swap the same element with itself.