数组分区(用C语言)
发布网友
发布时间:2022-05-14 01:30
我来回答
共1个回答
热心网友
时间:2023-11-19 04:41
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 20
void CountEvensAndOdds(int Array[], int Array_num, int *Evens_num, int *Odds_num)
{
int i;
for(i=0;i<Array_num;i++)
{
if(Array[i]%2)
(*Evens_num)++;
else
(*Odds_num)++;
}
}void Partition(int Array[], int Array_num, int *ArrayEvens, int *Evens_num, int *ArrayOdds, int *Odds_num)
{
int i, j=0, k=0;
CountEvensAndOdds(Array, Array_num,Evens_num,Odds_num);
ArrayEvens = (int *)malloc(sizeof(int )* (*Evens_num));
ArrayOdds = (int *)malloc(sizeof(int )* (*Odds_num));
for(i=0;i<Array_num;i++)
{
if(Array[i]%2)
ArrayEvens[j++] = Array[i];
else
ArrayOdds[k++] = Array[i];
}
printf("\n奇数数组为:\n");
for(i=0;i<*Odds_num;i++)
printf("%d ",ArrayOdds[i]);
printf("\n奇数数组为:\n");
for(i=0;i<*Evens_num;i++)
printf("%d ",ArrayEvens[i]);
printf("\n");
}int main()
{
int ArrayTest[MAX], *ArrayEvens=NULL, *ArrayOdds=NULL;
int Odds_num=0, Evens_num=0, num=MAX;
int i;
srand((unsigned)time(NULL));
for(i=0;i<MAX;i++)
ArrayTest[i]=rand()%100;
printf("原数组为:\n");
for(i=0;i<MAX;i++)
printf("%d ",ArrayTest[i]);
Partition(ArrayTest, num, ArrayEvens, &Evens_num, ArrayOdds, &Odds_num); return 0;
} 运行后: