#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    2
    Rep Power
    0

    Thumbs up 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;
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,384
    Rep Power
    1871
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo