Today I am going to post a program that is going to find out the maximum and minimum element of an array. You will say that it is very easy. But here we are going to use the

__technique to solve this problem . This technique will be able to solve the problem in a much lesser time. Here is the code for you-__**Divide & Conquer****#include<stdio.h>**

int a[50],max,min;

void find(int i,int n){

int mid,max1,min1;

if(i==n)

max=min=a[i];

else if(i==n-1)

if(a[i]>=a[n-1]){

max=a[n];

min=a[i];

}

else{

max=a[i];

min=a[n];

}

else{

mid=(i+n)/2;

find(i,mid);

max1=max;

min1=min;

find(mid+1,n);

if(max<max1)

max=max1;

if(min>min1)

min=min1;

}

}

int main(){

int i,n;

printf("Enter size of array : ");

scanf("%d",&n);

printf("Enter elements in array-->\n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

max=min=a[0];

find(1,n-1);

printf("Minimum : %d",min);

printf("\nMaximum : %d",max);

return 0;

}NOTE : This code is compiled with GCC compiler under Linux environment Ubuntu 12.04 LTS Precise Pangolin.int a[50],max,min;

void find(int i,int n){

int mid,max1,min1;

if(i==n)

max=min=a[i];

else if(i==n-1)

if(a[i]>=a[n-1]){

max=a[n];

min=a[i];

}

else{

max=a[i];

min=a[n];

}

else{

mid=(i+n)/2;

find(i,mid);

max1=max;

min1=min;

find(mid+1,n);

if(max<max1)

max=max1;

if(min>min1)

min=min1;

}

}

int main(){

int i,n;

printf("Enter size of array : ");

scanf("%d",&n);

printf("Enter elements in array-->\n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

max=min=a[0];

find(1,n-1);

printf("Minimum : %d",min);

printf("\nMaximum : %d",max);

return 0;

}

nice code

ReplyDeletemadarchod!!! code galat hai.....bc

Deletemadarchod!!! code galat hai.....bc

Deletemadarchod!!! code galat hai.....bc

Deletewrong code..plz update it

Deletebhen k lode code galat hai..

Deletea

ReplyDeleteNOTE : This code is compiled with GCC compiler under Linux environment Ubuntu 12.04 LTS Precise Pangolin.....

ReplyDeleteCAN IT BE COMPILED ON TURBO C ????

Ofcourse it can be compiled on turbo c just youll have to use something to hold the output screen.

DeleteGood

ReplyDeletelittle mistake: in main function, call find(0,n-1), not find(1,n-1)

ReplyDeletethis algo works only for assending orders

ReplyDeleteno it is applicable to any input order

Deleteno you wrong..

Deleteplease enter 5 array element like..

24

56

45

26

94...

then you'll see that

maximum = 95

but

minimum = 26(which should be 24)

why...?

correct this:-

Deletein main function

call find(0,n-1), not find(1,n-1)

Its working!!!!Just replace find(1,n-1) with find(0,n-1)...

ReplyDeleteits wrong

ReplyDelete//Correction

Deleteelse if(i==n-1)

{

if(a[i]<=a[n])

{

max=a[n];

min=a[i];

}

else{

max=a[i];

min=a[n];

}

Also change find(0,n-1)

Reference to 'max' is ambigous

ReplyDelete