欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

调整数组使奇数(odd)全部都位于偶数(even)前面

程序员文章站 2024-01-31 08:22:40
...
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
void first_odd(int *str, int sz)
{
	int i = 0;
	int j = 0;
	int k = 0;
	int odd_count = 0;
	int even_count = 0;
	int* odd = malloc(sz*sizeof(int));
	if (odd == NULL)
	{
		perror("error");
	}
	odd=memset(odd, 0, sz*sizeof(int));
	int* even = malloc(sz*sizeof(int));
	if (even == NULL)
	{
		perror("error");
	}
	even=memset(even, 0, sz*sizeof(int));
	for (i = 0; i < sz; i++)
	{
		if ((str[i] & 1) == 1)
		{
			odd[j++] = str[i];
			odd_count++;
		}
		else
		{
			even[k++] = str[i];
			even_count++;
		}
	}
	for (i = 0; i < odd_count; i++)
	{
		str[i] = odd[i];
	}
	for (j = 0; i <sz ; j++)
	{
		str[i++] = even[j];
	}
}
void show(int *str, int sz)
{
	if (sz > 0)
	{
		show(str, sz - 1);
		printf("%d ", *(str + sz-1));
	}
	else
	{
		str = 0;
	}
}
int main()
{
	/*int arr[] = { 1,2,3,4,5,6,7};*/
	int* arr[10] = { 0 };
	int i;
	srand((unsigned)time(NULL));//初始化随机数
	for (i = 0; i < 10; i++)
	{
		arr[i] = rand() % 100;
	}
	int sz = sizeof(arr) / sizeof(arr[0]);
	first_odd(arr, sz);
	show(arr, sz);
	system("pause");
	return 0;
}