Question

Prove binary search (Seen below) is correct using a loop invariant. def search_binary(arr, val): low, up...

Prove binary search (Seen below) is correct using a loop invariant.

def search_binary(arr, val):
    low, up = 0, len(arr) - 1
    while low != up:
        # binary search
        mid = (low + up) / 2

        if arr[mid] == val:
            return mid
        elif val < arr[mid]:
            up = mid - 1
        else:
            low = mid + 1

    return low

Homework Answers

Answer #1
def binsearch(int x, int[] A, int n)
    //@requires 0 <= n && n <= \length(A);
    //@requires is_sorted(A, 0, n);
    /*@ensures (-1 == \result && !is_in(x, A, 0, n))
    || ((0 <= \result && \result < n) && A[\result] == x);
    @*/
    { int lo = 0;
    int hi = n;
    while (lo < hi)
    //@loop_invariant 0 <= lo && lo <= hi && hi <= n;
    //@loop_invariant (lo == 0 || A[lo-1] < x);
    //@loop_invariant (hi == n || A[hi] > x);
        { int mid = lo + (hi-lo)/2;
        //@assert lo <= mid && mid < hi;
        if (A[mid] == x) return mid;
        else if (A[mid] < x) lo = mid+1;
        else /*@assert(A[mid] > x);@*/
        hi = mid;
        }
    return -1;
}

Drop a comment for any clarification or update, I would love to assist you.

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
how to pass in an object from an array of objects in a binary search on...
how to pass in an object from an array of objects in a binary search on swift? I have the following:    func binarySearchPrefix(array: [String], target: String) -> Bool {                var left = 0         var right = array.count - 1                while (left <= right) {             let mid = (left + right) / 2             let value = array[mid]             if (value.hasPrefix(target)) {                 return true             }             if (value < target) {                ...
Write a Java program that randomly generates an array of 500,000 integers between 0 and 499,999,...
Write a Java program that randomly generates an array of 500,000 integers between 0 and 499,999, and then prompts the user for a search key value. Estimate the execution time of invoking the linearSearch method in Listing A below. Sort the array and estimate the execution time of invoking the binarySearch method in Listing B below. You can use the following code template to obtain the execution time: long startTime = System.currentTimeMillis(); perform the task; long endTime = System.currentTimeMillis(); long...
For each pseudo-code function below (after the next ==== line), write a useful loop invariant capturing...
For each pseudo-code function below (after the next ==== line), write a useful loop invariant capturing correctness for the main loop in each of the following programs and briefly argue initialization, preservation, and termination. EXAMPLE PROBLEM: //Function to return the max of an array A Maximum(array of integers A) Local integer integer m m=0 for i = 1 to n if A[i] > m then m = A[i] end function Maximum EXAMPLE SOLUTION: The loop invariant is m = max(0,...
convert code from python to cpp L = [2,7,4,19,45,16,9,13,8,69,55,11,23,98,14,5,1,3]   #Merging function def merge(M,N): merging_list = []...
convert code from python to cpp L = [2,7,4,19,45,16,9,13,8,69,55,11,23,98,14,5,1,3]   #Merging function def merge(M,N): merging_list = []        //create empty list to merge the lists M and N if not M:                //if M is empty list, m = 0                //set m = 0 else: m = len(M)             //otherwise, set m = len(M) if not N:                //if N is empty list, n = 0       ...
Python 3 Rewrite KNN sample code using KNeighborsClassifier . ● Repeat KNN Step 1 – 5,...
Python 3 Rewrite KNN sample code using KNeighborsClassifier . ● Repeat KNN Step 1 – 5, for at least five times and calculate average accuracy to be your result. ● If you use the latest version of scikit -learn, you need to program with Python >= 3.5. ● Use the same dataset: “ iris.data ” ● Split your data: 67% for training and 33% for testing ● Draw a line chart: Use a “for loop” to change k from 1...
Do a trace on the binarySearch method below: variable key holds the value 17, and variable...
Do a trace on the binarySearch method below: variable key holds the value 17, and variable list is a reference to an array with these values {9, 20, 23, 28, 33, 38, 42, 48, 54, 61,73}. public static int binarySearch(int[] list, int key) {     int lowIndex = 0;     int highIndex = list.length - 1;     while (highIndex >= lowIndex) {       int midIndex = (lowIndex + highIndex) / 2;       if (key < list[midIndex]){            highIndex = midIndex...
The one missing piece was inserting into a binary search tree; we'll take care of that...
The one missing piece was inserting into a binary search tree; we'll take care of that today and write the insert function, as well as a height function. Both functions will be implemented in the "bst.h" header file, and tested using a provided main program in "main.cpp". Step one is to implement the insert function --- go ahead and modify "bst.h", adding the necessary code to (1) allocate a new node, and (b) link it into the tree. Once you...
convert this code to accept int value instead of float values using python. Make sure to...
convert this code to accept int value instead of float values using python. Make sure to follow the same code. do not change the steps and make sure to point to what code you replaced. make sure to have 2 files Method:----------------------- #define a python user difined method def get_float_val (prompt): is_num = False str_val = input (prompt) #prming read for our while #while is_num == False: (ignore this but it works) old school while not is_num: try: value =...
[15 pts.] Consider a version of a binary search tree (BST) for sorted maps with integer...
[15 pts.] Consider a version of a binary search tree (BST) for sorted maps with integer keys that stores additional information as data members of each node w of the tree to account for the smallest and largest integer keys in the subtree rooted at w. Suppose that we can access this information using w.min, for the smallest integer key, and w.max, for the largest. Algorithm 4 provides the pseudocode for the constructor of a node in a binary tree...
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...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT