This is a very basic algorithm(can't get simpler), but i am stumped. We have an array of elements and we have to determine the minimum and maximum.
Normal approach is to go through the array and find min and max which is 2n compares.
Slightly more efficient way would be to first compare consecutive elements of array in pair to determine max and min of any two elements(n/2 compares). We now have n/2 min and n/2 max elements. Now we can have final max and min in n/2 + n/2 + n/2(previous step) = 3/2* n or 1.5n compares
That's fine. Theoretically then the code should take less time to run in 2nd case as we are doing less compares. But when i run the code the results are otherwise.
My code snippet is below:
public class MinMax {
public static void nonEfficient(int [] array){
int min=array[0],max=array[0];
for (int anArray : array) {
if (anArray < min)
min = anArray;
else {
if (anArray > max)
max = anArray;
}
}
System.out.println("Max is :" + max);
System.out.println("Min is :" + min);
}
public static void efficient(int [] arr,int length){
int max,min;
max = min = arr[0];
int i = 0;
for (; i < length / 2; i++)
{
int number1 = arr[i * 2];
int number2 = arr[i * 2 + 1];
if (arr[i * 2] >= arr[i * 2 + 1])
{
if (number1 > max)
max = number1;
if (number2 < min)
min = number2;
}
else
{
if (number2 > max)
max = number2;
if (number1 < min)
min = number1;
}
}
if (i * 2 < length)
{
int num = arr[i * 2];
if (num > max)
max = num;
if (num < min)
min = num;
}
System.out.println("***********************");
System.out.println("Max is :" + max);
System.out.println("Min is :" + min);
}
public static void main(String[] args) {
int [] array = new int[10000000];
Random rand = new Random();
for(int i=0;i<array.length;i++)
array[i] = rand.nextInt(100000)-144;
long startTime = System.currentTimeMillis();
nonEfficient(array); //theoretically non efficient 2n compares
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);// just 11ms
startTime = System.currentTimeMillis();
efficient(array, 10000000);///theoretically more efficient 1.5n compares
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);//whooping 37 ms..what happpened ????
}
}
Could someone help me in figuring out what i am doing wrong. Is there something very obvious that i am missing.
Thanks for the help.