配列に格納されている隣同士の値を入れ替えるプログラムを作りたいのですが、入れ替え方が全く見当が付きません。
例えば、
入れ替え前
1 2 3 4 5 6
入れ替え後
2 1 4 3 6 5
お手伝いをお願いします。
配列の入れ替え方
Re: 配列の入れ替え方
素直に2個ずつ入れ替えればいいでしょう。
#include<stdio.h>
#define A 6
void irekae(int x, int *y);
int main(void)
{
int d[A] = {1,2,3,4,5,6 };
int i;
for (i = 0; i < A; i++){
printf("%2d", d[i]);
}
putchar('\n');
irekae(A, d);
for (i = 0; i < A; i++){
printf("%2d", d[i]);
}
putchar('\n');
return 0;
}
void irekae(int x, int *y)
{
int i;
for(i = 1; i < x; i += 2){
int tmp;
tmp = y[i - 1];
y[i - 1] = y[i];
y[i] = tmp;
}
}
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)
Re: 配列の入れ替え方
これはsequence pointの間でy[i-1]が複数回書き換えられているのでundefined behaviorであり、Wandboxで正常に動作しませんでした。
http://melpon.org/wandbox/permlink/XPGN64Gk9hbKCxyT
以下、N1256より引用
4. Conformance さんが書きました: 2 If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint is violated, the
behavior is undefined.
6.5 Expressions さんが書きました: 2 Between the previous and next sequence point an object shall have its stored value
modified at most once by the evaluation of an expression. Furthermore, the prior value
shall be read only to determine the value to be stored.
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)
Re: 配列の入れ替え方
申し訳ない。 と訂正します。みけCAT さんが書きました:これはsequence pointの間でy[i-1]が複数回書き換えられているのでundefined behaviorであり、Wandboxで正常に動作しませんでした。
http://melpon.org/wandbox/permlink/XPGN64Gk9hbKCxyT
以下、N1256より引用4. Conformance さんが書きました: 2 If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint is violated, the
behavior is undefined.6.5 Expressions さんが書きました: 2 Between the previous and next sequence point an object shall have its stored value
modified at most once by the evaluation of an expression. Furthermore, the prior value
shall be read only to determine the value to be stored.
Re: 配列の入れ替え方
#include<stdio.h>
#define SIZE 6
void irekae(int s[], int max);
int main(void)
{
int array[SIZE] = {1, 2, 3, 4, 5, 6};
int i;
printf("Array before arranged:");
for(i = 0; i < SIZE; i++)
printf("%2d", array[i]);
putchar('\n');
irekae(array,SIZE);
printf("Array after arranged: ");
for(i = 0; i < SIZE; i++)
printf("%2d", array[i]);
putchar('\n');
return 0;
}
void irekae(int s[], int max) {
void swap(int *a, int *b);
int i;
for(i = 0; i < max; i += 2)
swap(&s[i], &s[i+1]);
}
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}