Friday, July 19, 2013

Write the algorithm for finding the maximum and minimum

  Write the algorithm for finding the maximum and minimum  and explin?


The problem is to find the maximum and minimum items in a set of ‘n’ elements. 
Though this problem may look so simple as to be contrived, it allows us to demonstrate
divide-and-comquer in simple setting. 
Algorithm straight MaxMin(a,n,max,min)
//set max to the maximum and min to the minimum of a[1:n]
{
max := min: = a[i];
for i = 2 to n do
{
if(a[i] >max) then max: = a[i];
if(a[i] >min) then min: = a[i];
}
}
Algorithm maxmin(I,j,max,min)
{
if( I = j) then max := min:=a[I];
else if(I=j-1) then
{
if(a[I]<a[j]) then
{
max := a[j];min := a[I];
}
else
{
max:=a[I];
min := a[j]; }}
else
{
mid := [(I+j)/2];
maxmin(I,mid,max,min);
maxmin(mid+1,j,max1,min1);
if(max<max1) then max := max1;
if(min>min1) then min:=min1;

}} 

No comments:

Post a Comment