I believe that Java TreeSet has a balanced tree implementation which can perform tree sort(a lot like the quick sort) quickly. My recently-encountered problem shows that it seems to be performing more comparisons that I expect.
Does every balanced tree perform like Java's TreeSet on sort(insert), or is my performance testing approach wrong?
My code:
package expri.johnny.treeSortCompTimes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetCompTimeTest {
public static void main(String[] args) {
int size=1000;
ArrayList<Integer> ay =new ArrayList<>(size);
int treeHeight = (int) (Math.log (size)/Math.log (2));
System.out.println("tree height: "+treeHeight);
System.out.println("when size is "+ size + ",i expected compare tmies are: "+((treeHeight+1)*treeHeight/2));
for(int i =0,l=size-1;i<=l;i++){
ay.add(i);
}
Collections.shuffle(ay);
System.out.println(ay);
CountComp cc =new CountComp();
TreeSet<Integer> ts =new TreeSet<>(cc);
ts.addAll(ay);
cc.speakCount();
}
private static class CountComp implements Comparator<Integer>{
int counter =0;
@Override
public int compare(Integer o1, Integer o2) {
this.counter++;
int df = o1-o2;
if(df>0){
return 1;
}else if(df==0){
return 0;
}else{
return -1;
}
}
public void speakCount(){
System.out.println("total compared times: "+this.counter);
//when size is 100,i expected compare tmies are: 21
//total compared times: 545
//when size is 1000,i expected compare tmies are: 45
//however, the real total compared times: 8783
}
}
}
well , that is what is in my mind before:
10 compares for add
10 compares for add
10 compares for add
10 compares for add
10 compares for add
10 ...
10
10
10
10
10
10 -997th , what i thought was 7
10 -998th , what i thought was 8
10 - 999th , what i thought was 9
10 - 1000th , what i thought was 10
8547
i make big laughing material this time , hahaha!