天天看点

c语言求两个整数中的最大值和最小值,使用分治法,求n个整数中的最大值和最小值。运行正确可结果错误...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

#include "stdio.h"

#include "stdlib.h"

#define N 10

int *getRandNum(int n,int lower,int upper)

{

int *num;

int i;

num = (int *)malloc(sizeof(int) *n);

srand(time(NULL));

for(i=0;i

{

num[i] = (rand()%upper-lower+1) + lower;

}

return num;

}

// extremeValue[0]和extremeValue[1]分别代表最小值和最大值

int *getExtremeValue(int *num,int start,int end)

{

int *extremeValue;

int *temp1, *temp2;

int mid;

extremeValue = (int*)malloc(sizeof(int)* 2);

if(start==end)

{

extremeValue[0]=extremeValue[1]=num[start];

return extremeValue;

}

if(start == end-1)

{

if(num[start]

{

extremeValue[0]==num[start];

extremeValue[1]==num[end];

}

else

{

extremeValue[0]==num[end];

extremeValue[1]==num[start];

}

return extremeValue;

}

mid = (start + end) / 2;

temp1=getExtremeValue(num,start,mid);

temp2=getExtremeValue(num,mid+1,end);

if(temp1[0]

{

extremeValue[0]=temp1[0];

}

else

{

extremeValue[0]=temp2[0];

}

if(temp1[1]

{

extremeValue[1]=temp2[1];

}

else

{

extremeValue[1]=temp1[1];

}

free(temp1);

free(temp2);

return extremeValue;

}

int main()

{

int i,*num,*extremeValue;

num = getRandNum(N,100,1000);

for(i=0;i

{

printf("%d ",num[i]);

}

printf("/n");

extremeValue = getExtremeValue(num,0,N-1);

printf("Min:%d,Max:%d",extremeValue[0],extremeValue[1]);

return 0;

}