This Programs finds maximum and minimum Numbers from an Input array with the smallest number of Comparisons.It basically compare between successive two numbers and stores maximum(or minimum) among them and creates a sub-array with those maximums(or minimums) and performs a recursive algorithm in sub-array i.e again find maximum among two successive and creates sub-array with those.
The very last element in the last sub-array will be maximum(or minimum).
Maximum & Minimum Number
- #include<stdio.h>
- void func(int max[],int min[],int no);
- int cnt=0;//counting the comparison
- int main()
- {
- int num[100],max[50],min[50];
- int no,nom,i,j=0;
- printf("\nHow many numbers you want to enter:-");
- scanf("%d",&no);
- printf("\n");
- //inputting the number
- for(i=0;i<no;i++)
- {
- printf("Enter number %d:-",i+1);
- scanf("%d",&num[i]);
- }
- //checking if n is odd or not
- if(no%2==0)
- {nom=no;}
- else
- {
- nom=no-1;
- max[nom/2]=num[nom];
- min[nom/2]=num[nom];
- }
- i=0;
- //dividing the max and min array
- while(i<nom-1)
- {
- if(num[i]>num[i+1])
- {
- max[j]=num[i];
- min[j]=num[i+1];
- }
- else
- {
- max[j]=num[i+1];
- min[j]=num[i];
- }
- cnt++;
- i+=2;
- j++;
- }
- //calling the function to determine max and min by sending max,min and no. of elements
- if(no%2==0)
- func(max,min,no/2);
- else
- func(max,min,(no/2)+1);
- //output
- printf("\nThe total number you have given is %d and the comparisons are %d.",no,cnt);
- if(cnt!=0)
- {
- printf("\nThe maximum number is %d.",max[0]);
- printf("\nThe minimum number is %d.\n",min[0]);
- }
- else
- printf("\nError in evaluating Maximum and minimum numbers.\n");
- printf("\n");
- }
- void func(int max[],int min[],int no)
- {
- int i=0,j=0,nom;
- if(no%2==0) nom=no;
- else
- {
- nom=no-1;
- }
- while(i<nom-1)
- {
- //for maxm
- if(max[i]>max[i+1])
- max[j]=max[i];
- else
- max[j]=max[i+1];
- //for minm
- if(min[i]<min[i+1])
- min[j]=min[i];
- else
- min[j]=min[i+1];
- i+=2;
- j++;
- cnt+=2;//for two comparisons
- }
- if(no%2!=0)
- {
- max[nom/2]=max[nom];
- min[nom/2]=min[nom];
- }
- if(nom/2>=1)
- {
- if(no%2==0) func(max,min,nom/2);
- else func(max,min,(nom/2)+1);
- }
- }
Further Discussion will be carried out later.
Any suggestion is solicited.
0 Responses to Maximum Number Finding By Smallest Comparisons – C Programming