调整奇数偶数顺序,使数组奇数放在偶数之前

问题:

1.swap和print顺序写反

2.swap中right初值为0

void print_arr(int arr[], int length)
{
	int i = 0;
	for (i = 0; i < length; i++)
	{
		printf("%d ", arr[i]);
	}
}
void swap(int arr[], int length)
{
	int left = 0;
	int right = length - 1;
	while (left < right)
	{
		//
		while ((left < right) && (arr[left] % 2 == 1))
		{
			left++;
		}
		//
		while ((left < right) && (arr[right] % 2 == 0))
		{
			right--;
		}
		//交换奇偶数
		if (left < right)
		{
			int temp = arr[left];
			arr[left] = arr[right];
			arr[right] = temp;
		}
	}
}
int main()
{
	int arr[] = { 2,54,3,5,1,46,0,34,72,5,43,11,63 };
	int length = sizeof(arr) / sizeof(arr[0]); 
	swap(arr, length);
	print_arr(arr, length);
	/*int i = 0;
	for ( i = 0; i < length; i++)
	{
		if (arr[i] % 2 == 1)
		{
			printf("%d ", arr[i]);
		}
	}
	for (i = 0; i < length; i++)
	{
		if (arr[i] % 2 == 0)
		{
			printf("%d ", arr[i]);
		}
	}*/
	return 0;
}

你可能感兴趣的:(算法,数据结构)