Question: JAVA Use the empty stub method to implement a faster alternative for the intersection algorithm. public List intersectionFast(int[] a, int[] b) Assume that each array
JAVA
Use the empty stub method to implement a faster alternative for the intersection algorithm.
public List
Assume that each array has no duplicate values.
Steps for Completion
1. 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).
Given Code: import java.util.Arrays; import java.util.LinkedList; import java.util.List;
public class SimpleIntersection {
private BinarySearch search = new BinarySearch();
public List
public List 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 } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
