J
jimgardener
i tried diff ways to find min and max of a double[] .one using for
loops and the other with Arrays.sort
public void findmaxdemo1(){
double[] testarray=new double[]{-1.2,4.3,7,0,2.1,0.0,2.5};
long start=System.nanoTime();
double max=testarray[testarray.length-1];
double min=testarray[0];
for(int i=0;i<testarray.length;i++){
max=max>testarray?max:testarray;
min=min<testarray?min:testarray;
}
long end=System.nanoTime();
debug("min:"+min);
debug("max:"+max);
debug("by for loops took:"+(end-start));
}
public void findmaxdemo2(){
double[] testarray=new double[]{-1.2,4.3,7,0,2.1,0.0,2.5};
long start=System.nanoTime();
Arrays.sort(testarray);
double max=testarray[testarray.length-1];
double min=testarray[0];
long end=System.nanoTime();
debug("min:"+min);
debug("max:"+max);
debug("by Array took:"+(end-start));
}
public static void debug(String msg){
System.out.println(msg);
}
i find that the method using Arrays.sort takes more time than the
first one..i would like to know if the first one can be made faster?
I am not familiar with alg.analysis methods.Can someone advise as to
how i can find the max and min more efficiently
thanks
jim
loops and the other with Arrays.sort
public void findmaxdemo1(){
double[] testarray=new double[]{-1.2,4.3,7,0,2.1,0.0,2.5};
long start=System.nanoTime();
double max=testarray[testarray.length-1];
double min=testarray[0];
for(int i=0;i<testarray.length;i++){
max=max>testarray?max:testarray;
min=min<testarray?min:testarray;
}
long end=System.nanoTime();
debug("min:"+min);
debug("max:"+max);
debug("by for loops took:"+(end-start));
}
public void findmaxdemo2(){
double[] testarray=new double[]{-1.2,4.3,7,0,2.1,0.0,2.5};
long start=System.nanoTime();
Arrays.sort(testarray);
double max=testarray[testarray.length-1];
double min=testarray[0];
long end=System.nanoTime();
debug("min:"+min);
debug("max:"+max);
debug("by Array took:"+(end-start));
}
public static void debug(String msg){
System.out.println(msg);
}
i find that the method using Arrays.sort takes more time than the
first one..i would like to know if the first one can be made faster?
I am not familiar with alg.analysis methods.Can someone advise as to
how i can find the max and min more efficiently
thanks
jim