processci

1 Ocak 2011 Cumartesi

Find min and max-Divide and conquer approach

Divide and Conquer approach is an economic way to implement your programs while inputs are going to be a chaos to calculate. This approach makes things easier for machines.

At the first look over the problem, we have a long list of numbers which are not ordered. So easiest way to find maximum and minimum from this array is to get them in order and get index-0 and index-last. This is a challange when index-last is equal to (for example) 1 billion. So we may get things lighter for computing.

So this is the way I think:
  1. If we have 2 elements or 1, we may find min and max by comparison.
  2. Else if we have more than 2 elements in input array, we may divide them into halfs.
This recursion is a good approach.I wrote some explaining code here.

#typedef struct{ int min, max;
}Struct mm;

mm min_max( int array[] )
{   mm result;
    int length=array.length;

 if ( length >2)
    { int array1[ (length/2) ],
           array2[ (length/2)];                     // think if lenght cannot be divided into same halfs                    
      mm result1, result2;
    
     assign(array, array1, array2);           // think this funtion

      result1= min_max(array1);   
      result2= min_max(array2);

     if (result1.max >= result2.max)
          result.max = result1.max ;
         else result.max = result2.max;           

     if (result1.min <= result2.min )   
         result.min = result1.min;   
         else result.min = result2.min;

    return result; 
   }

else {
  if (array[0] >= array[1])     
     {
        result.min = array[1];
        result.max = array[2];
    return result; 
   }
 
   else {
           result.max = array[1];
           result.min = array[0];
   } //end of 2nd else
 } // end of 1st else

}//end of function

This code will help you to implement some economic recursive function. :) Thanks for reading.

1 yorum:

  1. Good Blog. Here also a helpful blog which is discussed with algorithm, Time Complexity as well as Comparison with Straight forward method:
    http://somnathkayal.blogspot.in/2012/08/finding-maximum-and-minimum-using.html

    YanıtlaSil