
December 25th, 2012, 04:12 AM
|
|
Registered User
|
|
Join Date: Dec 2012
Posts: 2
Time spent in forums: 40 m 52 sec
Reputation Power: 0
|
|
Problem in divide and conquer approach to find max-min in an array
I wrote a program to find max-min in array using divide and conquer approach, but the code gives incorrect results. Can anyone help me fix the problem-
Code:
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
int maxmin(int,int,int *,int *);
int num[20];
main()
{
int max,min; int n,i;
printf("enter number of elements in the array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the number\n");
scanf("%d",&num[i]);
}
maxmin(0,n-1,&max,&min);
printf("the maximum element is- %d\n",max);
printf("the minimum element is- %d\n",min);
getch();
}
maxmin(int i,int j,int *max,int *min)
{ int max1,min1;
if(i==j) *max=*min=num[i];
else if(j==(i+1)) { if(num[i]<num[j]) { *max=num[j]; *min=num[i];}
else if(num[i]>num[j]){*max=num[i]; *min=num[j];}
else *max=*min=num[i];
}
else
{
int mid=(i+j)/2;
maxmin(i,mid,max,min);
maxmin(mid+1,j,&max1,&min1);
}
if(*max<max1) *max=max1;
if(*min>min1) *min=min1;
}
|