Question

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 22, and the predecessor of 5 is not defined. The predecessor problem has remarkable applications in network routing, where we send information from one computer to another, making email and other uses of the internet possible.
Another application is nearest-neighbor search, akin to locating restaurants on Google Maps, where it returns the closest match to a cuisine of your choice.
Our task is to find predecessor of a number in an array using a Binary Search approach. To this end, complete the following function:
- int ndPredecessor(int A[ ], int arrayLen, int key): returns a position in the array A where the predecessor of key lies. Needless to say that the array A is sorted in ascending order. If the predecessor of key is not defined, return -1.

Caution: You MUST use a binary search approach. Thus, the complexity should be O(log n). If your code ends up scanning the entire array (has a complexity O(n)), your work won't be counted.

Homework Answers

Answer #1

// Program for predecessor

public class Main
{

    private static int predecessor (int array[], int arrayLen, int key)
    {
        // To check if the solution exists or not
        if (key<array[0])
        {
            return -1;
        }
        // To check wheather the value is greater than all the values
        else if (key>array[arrayLen-1]){
            return arrayLen-1;
        }

        else{
            // Binary search approach
            int first_value=0;
            int last_value=arrayLen;
            int middle = (first_value + last_value) / 2;
            while (first_value <= last_value)
            {
                if (array[middle] < key)
                {
                    first_value = middle + 1;
                }
                else if (array[middle] == key)
                {
                    return middle;
                }
                else
                {
                    last_value = middle - 1;
                }
                middle = (first_value + last_value) / 2;
            }


                return last_value;
        }
    }
    public static void main (String[]args)

    {
        int[] intArray = new int[]{ 6,9,10,13,22,31,34,88 };
        System.out.println("Predecessor for 5 exist at : "+predecessor(intArray,8,5));
        System.out.println("Predecessor for 31 exist at : "+predecessor(intArray,8,31));
        System.out.println("Predecessor for 30 exist at : "+predecessor(intArray,8,30));
    }
}

// Output of the program

Predecessor for 5 exist at : -1
Predecessor for 31 exist at : 5
Predecessor for 30 exist at : 4

Process finished with exit code 0

// Image for code

// Continued Program

// Output screeshot

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 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;...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g,...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords)] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) What int setup_game needs to do setup_game() does exactly what the name suggests. It sets up a new game of hangman. This means that it picks a random word from the supplied wordlist array and...
In this lab, you will write a program that creates a binary search tree based on...
In this lab, you will write a program that creates a binary search tree based on user input. Then, the user will indicate what order to print the values in. **Please write in C code** Start with the bst.h and bst.c base code provided to you. You will need to modify the source and header file to complete this lab. bst.h: #ifndef BST_H #define BST_H typedef struct BSTNode { int value; struct BSTNode* left; struct BSTNode* right; } BSTNode; BSTNode*...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as possible: What is a checked exception, and what is an unchecked exception? What is NullPointerException? Which of the following statements (if any) will throw an exception? If no exception is thrown, what is the output? 1: System.out.println( 1 / 0 ); 2: System.out.println( 1.0 / 0 ); Point out the problem in the following code. Does the code throw any exceptions? 1: long value...
**please write code with function definition taking in input and use given variable names** for e.g....
**please write code with function definition taking in input and use given variable names** for e.g. List matchNames(List inputNames, List secRecords) Java or Python Please Note:    * The function is expected to return a STRING_ARRAY.      * The function accepts following parameters:      *  1. STRING_ARRAY inputNames      *  2. STRING_ARRAY secRecords      */ Problem Statement Introduction Imagine you are helping the Security Exchange Commission (SEC) respond to anonymous tips. One of the biggest problems the team faces is handling the transcription of the companies reported...
Using the model proposed by Lafley and Charan, analyze how Apigee was able to drive innovation....
Using the model proposed by Lafley and Charan, analyze how Apigee was able to drive innovation. case:    W17400 APIGEE: PEOPLE MANAGEMENT PRACTICES AND THE CHALLENGE OF GROWTH Ranjeet Nambudiri, S. Ramnarayan, and Catherine Xavier wrote this case solely to provide material for class discussion. The authors do not intend to illustrate either effective or ineffective handling of a managerial situation. The authors may have disguised certain names and other identifying information to protect confidentiality. This publication may not be...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT