阵列的输入是{4,13,9,10,17,25,35,40,29,48,52,12,15,71,27,32}。我需要比较每两个元素,如4和13,更大的元素进入临时数组,并与数组中的下一个元素进行比较,依此类推。
我有这个代码,它给了我数组 {} 13,10,25,40,48,52,71,32,13,40,52,71,40,71 我需要输出如下面的数组 {4,13,13,13,17,25,35,40,40,48,52,52,52,71,71,71}
#include <stdio.h>
int main()
{
int pairmax(int[], int);
int premax(int[], int);
int i, j, max1, max2, n;
n=16;
int x[16]={4, 13, 9, 10, 17, 25, 35, 40, 29, 48, 52, 12, 15, 71, 27, 32};
max1 = pairmax(x,n);
max2 = premax(x, n);
printf("Pairwise max: Largest = %d\n",max1);
printf("Prefix max: Largest = %d\n",max2);
}
int pairmax(int x[], int n) // Implementation of Pairwise Max
{
int max(int, int);
int y[10], i, j;
if (n==2)
return max(x[0], x[1]);
for(i=0, j=0; i<n;i+=2,j++)
{
if(i < n-1)
y[j] = max(x[i], x[i+1]);
else
y[j] = x[i];
printf("Prefix max: Largest = %d\n",y[j]);
}
return pairmax(y,j);
}
int premax(int x[], int n) // Implementation of Prefix Max
{
int max(int, int);
int large, i;
large = x[0];
for(i=1; i<n;i++)
large = max(large,x[i]);
return large;
}
int max(int a, int b)
{
if (a > b)
return a;
else
return b;
}
答案 0 :(得分:0)
#include <stdio.h>
int main(void){
int array[] = {4, 13, 9, 10, 17, 25, 35, 40, 29, 48, 52, 12, 15, 71, 27, 32};
int size = sizeof(array)/sizeof(*array);
int max = array[0];
int result[size];
for(int i = 0; i < size; ++i){
if(max < array[i])
max = array[i];
result[i] = max;
}
//print result
putchar('{');
for(int i = 0; i < size; ++i){
if(i)
putchar(',');
printf("%d", result[i]);
}
putchar('}');
putchar('\n');
return 0;
}