C语言19弹--交换数组元素

使用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;
}

你可能感兴趣的:(c语言,算法,开发语言)