public static LLList intersect(LLList list1, LLList list2) { LLList inters = new LLList(); for (int i = 0; i lt; list1.length(); i++) { Object item1…

public static LLList intersect(LLList list1, LLList list2) {

  LLList inters = new LLList();

  for (int i = 0; i < list1.length(); i++) {

    Object item1 = list1.getItem(i);

    for (int j = 0; j < list2.length(); j++) {

      Object item2 = list2.getItem(j);

      if (item2.equals(item1)) {

        inters.addItem(item2, inters.length());

        break;  // move onto the next item from list1

      }

    }

  }

  return inters;

}

How to improve the efficiency of this method? I am thinking maybe it can be sorted before the for loops, but not sure how to implement it.

Also, what is the worst-case running time of this algorithm as a function of the length 

Leave a Reply