111,125
社区成员
发帖
与我相关
我的任务
分享"java"
public class Test4 {
private static Random ran;
private int[] source;
private int min = 0;
private int max = 0;
private int compareCount = 0;
static{
ran = new Random();
}
public static void main(String...args){
Test4 t = new Test4();
t.init();
// t.printRan();
t.findMinMax(0);//2000
t.print();
t.findMinMax(1);//199X
t.print();
}
private void printRan() {
for(int i : source){
System.out.println(i);
}
}
private void init(){
//here I give 1000 numbers to test
source = new int[1000];
for(int i=0;i<source.length;i++){
source[i] = this.geneInt();
}
}
private int geneInt(){
return ran.nextInt();
}
private void print(){
System.out.println("Min:"+this.min);
System.out.println("Max:"+this.max);
System.out.println("compareCount:"+this.compareCount);
}
private int getBig(int a,int b){
this.compareCount++;
return a>b?a:b;
}
private int getSmall(int a, int b){
this.compareCount++;
return a<b ?a:b;
}
/**
* @param mode 0 means if a is large than max, no need to compare with min, so vice versa
*/
private void findMinMax(int mode){
this.min = source[0];
this.max = source[0];
this.compareCount = 0;
if(mode==0){
for(int a: source){
this.max = this.getBig(a, this.max);
this.min = this.getSmall(a, this.min);
}
}
if(mode==1){
for(int a: source){
if(this.max<this.getBig(a, this.max)){
this.max = a;
}else if(this.min>this.getSmall(a, this.min)){
this.min = a;
}
}
}
}
}