Question

Complete this function (the instructions are below the code): private static int numCommonElements(int A[], int B[],...

Complete this function (the instructions are below the code):

private static int numCommonElements(int A[], int B[], int lenA, int lenB) {
// Complete this function.
}

We want to solve the following problem: given two sorted arrays A[n] and B[m] of length n and m respectively, we want to nd the number of elements that are common to both the arrays (without repeated counting of the same element).
For example, the arrays A[ ] = {7; 13; 19; 20; 22; 22; 37; 37} and B[ ] = {7; 14; 17; 22; 28; 31; 37; 37; 37; 43}, both have 7, 22 and 37; hence, the count is 3. (Note that we count 22 and 37 only once.)
On the other hand, A[ ] = {7; 13; 19; 20; 22} and B[ ] = {14; 17; 21; 28} have nothing in common; hence, the count is 0.
One algorithm for solving this problem is as follows: pick each number in array A and then scan array B to verify if the number exists. It is easy to see that the Big-O complexity of this procedure is O(mn). As you may have guessed, this algorithm is pretty slow.
Our task is to devise a faster algorithm, based on binary search. To this end, complete the following function:
- int numCommonElements(int A[ ], int B[ ], int lenA, int lenB): returns the number of elements that are present in both arrays A and B. Returns 0 if none of the elements are
common. It should not double count any element.
Caution: You algorithm must have a complexity of O(N logN), where N = max{n;m} is the maximum of n and m, i.e., N is the maximum of the length of the two arrays. If your code ends up having a complexity of O(N2), your work won't be counted. If you write a code having complexity better than O(N logN), such as O(N), you will have to provide a write-up explaining why your code works, and why the complexity is O(N).

Homework Answers

Answer #1

Program in java:

//importing required package
import java.util.ArrayList;
import java.util.List;
//class declaration
public class CommonElement {
    //main method
    public static void main(String[] args) {
        //initiallizing the arrays
        int A[] = {7,13, 19, 20, 22, 22, 37, 37};
        int B[] = {7, 14, 17, 22, 28, 31, 37, 37, 37, 43};
        //calling function to obtain the common element
        numCommonElements(A, B, A.length, B.length);
    }
    //method to find the common element
    private static int numCommonElements(int A[], int B[], int lenA, int lenB) {
        // creating list to store the common elements
        List<Integer> number=new ArrayList<>();
        //variable declaration
        int element;
        boolean flag;
        //running the loop to find the common number
        for(int i=0;i<lenA;i++){
            //calling binary search to obtain common element
            element=binSearch(B, 0, lenB, A[i]);
            //if the value of the element is not equal to -1 means the element is common to both arrays
            if(element!=-1){
                flag=true;
                //searching in the array list if the number is already present, if not add the common element
                for(int j=0;j<number.size();j++){
                    if(element==number.get(j)){
                        flag=false;
                        break;
                    }
                }
                //adding common element to the common element list
                if(flag!=false){
                    number.add(element);
                    flag=true;
                }
              
            }
        }
        //printing the common element
        System.out.println(number);
        //printing the count of common element
        System.out.println(number.size());
        return 0;
    }
    private static int binSearch(int ar[], int left, int right, int num)
    {
        if (right >= left) {
            int middle = left + (right - left) / 2;

            // If the element is present at the
            // middle itself
            if (ar[middle] == num)
                return num;

            // If element is smaller than mid, then
            // it can only be present in left subarray
            if (ar[middle] > num)
                return binSearch(ar, left, middle - 1, num);

            // Else the element can only be present
            // in right subarray
            return binSearch(ar, middle + 1, right, num);
        }

        // We reach here when element is not present
        // in array
        return -1;
    }
}

Output:

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Complete the following function (detailed instructions are given below the code): private static int predecessor(int array[],...
Complete the following function (detailed instructions are given below the code): private static int predecessor(int array[], int arrayLen, int key) { // Complete this function. } Given a set of numbers, the predecessor of a number x is the highest number in the set that is less than or equal to x. Thus, if I have the set {6; 9; 10; 13; 22; 31; 34; 88}, then the predecessor of 31 is 31 itself, whereas the predecessor of 30 is...
How to measure the time complexity of an algorithm? Identify an important operation in the algorithm...
How to measure the time complexity of an algorithm? Identify an important operation in the algorithm that is executed most frequently. Express the number of times it is executed as a function of N. Convert this expression into the Big-O notation. A. For each of the three fragments of code, what is its worst-case time complexity, in the form "O(…)". (Use the given solution to the first problem as a model)                 //----------------- This is a sample problem – solved ------...
/************************************************************************************* Function Prototypes *************************************************************************************/ int ScanArray(char *fname, int myArray[], int nSize); void Ge
/************************************************************************************* Function Prototypes *************************************************************************************/ int ScanArray(char *fname, int myArray[], int nSize); void GenerateFromArray(void); /************************************************************************************/ /************************************************************************************/ int main(void) { /* This is the main() program. It should call the functions ScanArray() and GenerateFromArray() */ GenerateFromArray(); system("pause"); return 0; } /*************************************************************************************** Define this function to scan the elements of an array from the given data file "ArrayInp.dat". If the input file is not found, or contains invalid data, the function should return a 0 and print an error message. If the input...
Consider the following function: 01: void cpUniq (const int* source, int N, vector<int>& dest) 02: {...
Consider the following function: 01: void cpUniq (const int* source, int N, vector<int>& dest) 02: { 03: list<int> L; 04: for (int i = 0; i < N; ++i) 05: { 06: copy (source, source + i, front_inserter<int>(L)); 07: } 08: for (int j: L) 09: { 10: if (find(dest.begin(), dest.end(), j) != dest.end()) 11: dest.push_back(j); 12: } 13: } and the following list of complexity values: A: O(1), B: O(log N), C: O(N), D: O(N log N), E: O(N2),...
Below is C code and Python code for an algorithm. C code: void foo( int n,...
Below is C code and Python code for an algorithm. C code: void foo( int n, int A, int B, int C ) { if( n==1 ) { printf("%d to %d\n",A,B); return; } foo( n-1, A, C, B ); printf("%d to %d\n",A,B); foo( n-1, B, C, A ); Python code: def foo(n , A, B, C): if n==1: print A, "to", B return foo(n-1, A, C, B) print A, "to", B foo(n-1, B, C, A) Let Hn be the number...
Restricted structures such as stack and queue are fast, but they do not support access in...
Restricted structures such as stack and queue are fast, but they do not support access in the key field mode. Group of answer choices True False Big O analysis evaluates an algorithm based on its _________ performance. Group of answer choices A. average-case B. best-case C. worst-case Which of the following algorithms is the fastest in speed? Group of answer choices A. Polynomial time algorithm B. Linear time algorithm C. Exponential time algorithm The following code gives an implementation of...
Write a MIPS assembly program that sorts an array using bubble sort translating the C code...
Write a MIPS assembly program that sorts an array using bubble sort translating the C code int main(void) { int array[] = {10, 2, 7, 5, 15, 30, 8, 6}; // input array int arraySize = sizeof(array)/sizeof(array[0]); bool swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; //Note : "j" , "arraySize - j" are optimizations to the bubble sort algorithm j++; // j= sorted elements int i=0; /* "arraySize - j" is used...
Please post all code in Pseudo code. Please post ORIGINAL answers do not copy from similar...
Please post all code in Pseudo code. Please post ORIGINAL answers do not copy from similar questions. Please post in a format that can be directly copied. Reasoning on answers would be most helpful but not required. Thank you in advance for your help. 1.Design an algorithm to find all the common elements in two sorted lists of numbers. For example, for the lists 2, 5, 5, 5 and 2, 2, 3, 5, 5, 7, the output should be 2,...
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    //...
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    // STEP 1 -- Make sorting methods generic    ///////////////////////////////////////////////       /**    * Re-orders the contents given array using the insertion sort algorithm.    *    * @param data The array to be sorted.    */    //TODO: Make me generic to work on any kind of Comparable data!    public static void insertionSort(int[] data)    {        int insert; // temporary...
C CODE PLZ! All instructions are in sections of code #include <stdio.h> /* TODO: Define 3...
C CODE PLZ! All instructions are in sections of code #include <stdio.h> /* TODO: Define 3 functions input, gcd and lcm in such a way that the main function below compiles correctly and has the correct behavior. The input function prompts the user to enter a non-negative integer. If the user enters a negative integer, the function prints a "sorry" statement and prompts the user again. It keeps on prompting until the user enters a non-negative number. The input function...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT