使用C语言实现交换数组元素
思路:使用头尾下标通过使用三方变量实现交换,注意头尾变量相等时单独进行交换。
1.头交换
int tmp1 = arr1[left];
arr1[left] = arr2[left];
arr2[left] = tmp1;
2.尾交换
int tmp2 = arr1[right];
arr1[right] = arr2[right];
arr2[right] = tmp2;
3.相等时
if (left == right)
{
tmp1 = arr1[left];
arr1[left] = arr2[right];
arr2[right] = tmp1;
}
总代码
#include
int main()
{
int arr1[] = { 0,1,2,3,4 };
int arr2[] = { 5,6,7,8,9 };
int i = 0, j = 0;
int sz = sizeof(arr1) / sizeof(arr1[0]);
int left = 0, right = sz - 1;
printf("交换前\n");
for (i = 0; i < sz; i++)
{
printf("%d ", arr1[i]);
}
printf("\n");
for (i = 0; i < sz; i++)
{
printf("%d ", arr2[i]);
}
printf("\n");
while (left <= right)
{
int tmp1 = arr1[left];
arr1[left] = arr2[left];
arr2[left] = tmp1;
int tmp2 = arr1[right];
arr1[right] = arr2[right];
arr2[right] = tmp2;
if (left == right)
{
tmp1 = arr1[left];
arr1[left] = arr2[right];
arr2[right] = tmp1;
}
left++;
right--;
}
printf("交换后\n");
for (i = 0; i < sz; i++)
{
printf("%d ", arr1[i]);
}
printf("\n");
for (i = 0; i < sz; i++)
{
printf("%d ", arr2[i]);
}
printf("\n");
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58