C 言語の配列で要素の位置を入れ替えるにはどうすればよいですか。
C言語では、次のように配列内の2つの要素の位置を入れ替えることができます。
- 中間変数を介してスワップする
void swap(int* array, int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
- ビット演算のXORによる互換(整数の配列にのみ適用可能)
void swap(int* array, int index1, int index2) {
array[index1] = array[index1] ^ array[index2];
array[index2] = array[index1] ^ array[index2];
array[index1] = array[index1] ^ array[index2];
}
上記2つのメソッドを使用すれば、必要に応じて配列内の2つの任意の要素の位置を入れ替えています。