输入一个整数数组,实现一个函数,来调整该数组中数字的顺序使得数组中所有的奇数位于数组的前半部分,所有偶数位于数组的后半部分
//第一种方法:
#include
void reverse(int *p,int len)
{
int *start = p;
int *end = p + len - 1;
int tmp = 0;
while (start < end)
{
if ((*start) % 2 == 1)
{
start++;
}
else
{
if ((*end % 2 == 0))
{
end--;
}
else
{
tmp = *start;
*start = *end;
*end = tmp;
}
}
}
}
int main()
{
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int len = sizeof(arr) / sizeof(arr[0]);
reverse(arr,len);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
//第二种方法:
#include
void swap(int *pa, int*pb)
{
int tmp = *pa;
*pa = *pb;
*pb = tmp;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0])-1;
while (left < right)
{
while ((left < right) && (arr[left] % 2 == 1))
{
left++;
}
while ((left < right) && (arr[right] % 2 == 0))
{
right--;
}
if (left < right)
{
swap(&arr[left], &arr[right]);
left++;
right--;
}
}
int i = 0;
for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
当前标题:使数组中奇数位于偶数前面
当前URL:
http://bzwzjz.com/article/pccieg.html