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:
- If we have 2 elements or 1, we may find min and max by comparison.
- Else if we have more than 2 elements in input array, we may divide them into halfs.
#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.