java - Improving Intersection Algorithm -


i have algorithm build intersection of 2 sorted lists. if compare java.util.bitset in performance test, algorithm slow.

    public static list<integer> intersection(list<integer> list1, list<integer> list2) {             int size1 = list1.size(), size2 = list2.size();             int capacity = size1 < size2 ? size1 : size2;             list<integer> intersection = new arraylist<integer>(capacity);             int i1 = 0, i2 = 0;             while (i1 < size1 && i2 < size2) {                 if (list1.get(i1) < list2.get(i2))                     i1++;                 else if (list2.get(i2) < list1.get(i1))                     i2++;                 else {                     intersection.add(list2.get(i2++));                     i1++;                 }             }             return intersection;         } 

anyone sees improvement?

thanks

are inputs function of type arraylist?

  • if are, algorithmically there nothing wrong method. i'd make 2 changes:
    1. i'd change argument types arraylist<integer> list1, arraylist<integer> list2;
    2. i'd call list1.get(i1) , list2.get(i2) once. may or may not make difference performance, stylistically prefer factor out.
  • if need support list, i'd rewrite function in terms of 2 iterators, since calling get(index) expensive.

finally, when testing performance, make sure follow advice given in how write correct micro-benchmark in java?


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -