Question

In: Computer Science

Developing a Faster Intersection Algorithm Scenario We have already seen an algorithm that produces an intersection...

Developing a Faster Intersection Algorithm Scenario We have already seen an algorithm that produces an intersection between two input arrays in Snippet 1.6, shown below:

public List intersection(int[] a, int[] b) {

List result = new ArrayList<>(a.length);

for(int x : a) {

for(int y : b) {

if (x == y) result.add(x);

}

}

return result;

}

We have already shown how the runtime complexity of this algorithm is O(n2). Can we write an algorithm with a faster runtime complexity?

To find a solution for this problem, think about how you would you go about finding the intersection by hand between two decks of playing cards. Imagine you take a subset from each shuffled deck; which technique would you use to find the common cards between the first and second deck?

Aim

Improve the performance of the array intersection algorithm and reduce its runtime complexity.

Prerequisites

You will find two methods for improving the intersection: The slow intersection:

public List intersection(int[] a, int[] b)

The empty stub, returning null: public List intersectionFast(int[] a, int[] b)

Use the second, empty stub method, to implement a faster alternative for the intersection algorithm.

Assume that each array has no duplicate values.

Steps for Completion

Assume that we have a way to sort the inputs in O(n log n). This is provided in the following method:

public void mergeSort(int[] input) {

Arrays.sort(input);

}

We can use this method to sort one input array, or both, and make the intersection easier.

To sort one input array, we can use a binary search on it. The runtime complexity is O(n log n) for the merge sort plus O(n log n) for the binary search per item in the first list. This is nlog+ nlog n which results in a final O(n log n).

Sort both arrays, and have two pointers, one for each array.

Go through the input arrays in a linear fashion. Advance a pointer if the other pointer is pointing to a larger value.

If the values at both pointers are equal, both pointers are incremented. The runtime complexity for this algorithm is 2 (n log n) for the two merge sorts plus the n for the linear pass after the sorting. This results in 2 (n log n) + n with a final O(n log n).

CODE TO WORK WITH:

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class SimpleIntersection {

private BinarySearch search = new BinarySearch();

public List<Integer> intersection(int[] a, int[] b) {
List<Integer> result = new LinkedList<>();
for (int x : a) {
for (int y : b) {
if (x == y) result.add(x);
}
}
return result;
}

public List<Integer> intersectionFast(int[] a, int[] b) {
// Write your code here
return null;
}

public void mergeSort(int[] input) {
Arrays.sort(input);
}

public static void main(String[] args) {
Intersection inter = new Intersection();
System.out.println(inter.intersection(new int[]{4, 7, 5, 2, 3}, new int[]{4, 2, 3, 9, 1}));
System.out.println(inter.intersection(new int[]{4, 6, 11, 2, 3}, new int[]{5, 11, 3, 9, 1}));

// Write your code here

}
}

Solutions

Expert Solution

Points to consider:

  1. We need to sort the array
  2. Then we need to traverse both the arrays together.
  3. appending the common ones to the list.

Code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class SimpleIntersection {


public List<Integer> intersection(int[] a, int[] b) {
List<Integer> result = new LinkedList<>();
for (int x : a) {
for (int y : b) {
if (x == y) result.add(x);
}
}
return result;
}

public List<Integer> intersectionFast(int[] a, int[] b) {
// Write your code here
   mergeSort(a);
   mergeSort(b);
   List<Integer> list = new ArrayList<Integer>();
   int i =0, j = 0;
   while(i<a.length && j<b.length)
   {
       if(a[i]<b[j]) {
           i++;
       }
       else if(a[i] > b[j]) {
           j++;
       }
       else {
           list.add(a[i]);
           i++;j++;
       }
   }
   return list;
}

public void mergeSort(int[] input) {
   Arrays.sort(input);
}

public static void main(String[] args) {
SimpleIntersection inter = new SimpleIntersection();
System.out.println(inter.intersectionFast(new int[]{4, 7, 5, 2, 3}, new int[]{4, 2, 3, 9, 1}));
System.out.println(inter.intersectionFast(new int[]{4, 6, 11, 2, 3}, new int[]{5, 11, 3, 9, 1}));

// Write your code here

}
}

Sample output:

Friend, That was a nice question to answer
If you have any doubts in understanding do let me know in the comment section. I will be happy to help you further.
Please like it if you think effort deserves like.
Thanks


Related Solutions

As we have already seen, reason and emotions are an integral part of decision making. Cognitive...
As we have already seen, reason and emotions are an integral part of decision making. Cognitive processing--or the way we understand and acquire information--is also important to this process. But where does culture fit into the equation? For example, do people in Asian countries use the same logic when deciding as people in Europe or the United States? What influence do religious differences have over a person's ethical approach to solving a problem? 1. Let’s do a pretend exercise. Imagine...
As you have already seen, Excel does not have a function to calculate the payback period....
As you have already seen, Excel does not have a function to calculate the payback period. We have shown three ways to calculate the payback period, but there are numerous other methods as well. Below, the cash flows for a project are shown. You need to calculate the payback period using two different methods. A. Calculate the payback period in a table. The first three columns of the table will be the year, the cash flow for that year, and...
We have seen in lectures that if 50 people are chosen at random then there is...
We have seen in lectures that if 50 people are chosen at random then there is a 97% chance that at least two of them share the same birthday. Use similar calculations to answer the questions below. Assume that an ANU student is equally likely to have any one of 000 ... 999 as the last three digits of their ID number. (a) What is the percentage chance that in a working group of five students at least two have...
1.Use a developing country as an example to explain some economic have expanded faster than others...
1.Use a developing country as an example to explain some economic have expanded faster than others in the history. 2.What are the conditions or factors that impact growth and how do we measure growth?
Consider some of the disaster events we have experienced or that you have seen in the...
Consider some of the disaster events we have experienced or that you have seen in the news during the past few years, occurring locally, across a state, nationally, or globally. What event do you think is most likely to be the next "big" disaster? Tell why you chose this event, and what you think the Public Health Response system's role should be in responding to it.
1. We have seen that competitive balance is not quite as important to the demand of...
1. We have seen that competitive balance is not quite as important to the demand of sports leagues. But let’s say you were charged with improving the balance we see in a league. Given what was learned, what policies would you advocate to accomplish this objective? 2. Why does the NBA have less balance than other major North American sports?
a) we have seen, a lot of effort is involved in determining the cost of materials,...
a) we have seen, a lot of effort is involved in determining the cost of materials, labors and overhead in a manufacturing process. What’s the goal of all this effort? b)Assume that a company has met the goal described above, what does the company then do with the information obtained? c) Provide a specific example of the company’s use of the information gathered?
As we have seen this week, one of the more controversial issues with the representation of...
As we have seen this week, one of the more controversial issues with the representation of American Indians is the use of the terms "Indian" and Indian-related names with high school, college, and professional sports teams. Is this an issue that needs to be addressed, or is it something that people should just move past and ignore? Do you think these names should be kept to keep the tradition and merchandise relevant today, and/or that the names actual honor American...
As in the present scenario everybody is very busy in their regular work. We expect some intermediary to do our work faster and easier.
As in the present scenario everybody is very busy in their regular work. We expect some intermediary to do our work faster and easier. Financial intermediaries reallocate uninvested capital to productive enterprises through a variety of debt, equity, or hybrid stake holding structures As a student of financial management, what do you think financial intermediary in your own words, what are the primary role you expect from a financial intermediary to do your work faster and easier with any interruption...
Through the last decade, we have seen the impact business people have on our society. At...
Through the last decade, we have seen the impact business people have on our society. At the end of your career, what do you think people will say you did for society? Give an example of something you have already done that supports this characterization. Write in detail. plz ans asap....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT