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) {                ...
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...
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 =...
Develop a Traceroute application in python using ICMP. Your application will use ICMP but, in order...
Develop a Traceroute application in python using ICMP. Your application will use ICMP but, in order to keep it simple, will not exactly follow the official specification in RFC 1739.. Below you will find the skeleton code for the client. You are to complete the skeleton code. The places where you need to fill in code are marked with #Fill in start and #Fill in end. Code from socket import * import os import sys import struct import time import...
The Binary Search Tree implementation for bst.zip. The code in the destructor of the BST class...
The Binary Search Tree implementation for bst.zip. The code in the destructor of the BST class is empty. Complete the destructor so the memory allocated for each node in the BST is freed. Make a couple of different trees in your main method or in a function to test the destructor (the program should not crash upon exiting). bst.zip (includes the following files below in c++): bst.h: #pragma once #include #include "node.cpp" using namespace std; template class BST { public:...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any type dynamic arrays (replace string by the template in all instances below). • The class should have: – A private member variable called dynamicArray that references a dynamic array of type string. – A private member variable called size that holds the number of entries in the array. – A default constructor that sets the dynamic array to NULL and sets size to 0....
Strings The example program below, with a few notes following, shows how strings work in C++....
Strings The example program below, with a few notes following, shows how strings work in C++. Example 1: #include <iostream> using namespace std; int main() { string s="eggplant"; string t="okra"; cout<<s[2]<<endl; cout<< s.length()<<endl; ​//prints 8 cout<<s.substr(1,4)<<endl; ​//prints ggpl...kind of like a slice, but the second num is the length of the piece cout<<s+t<<endl; //concatenates: prints eggplantokra cout<<s+"a"<<endl; cout<<s.append("a")<<endl; ​//prints eggplanta: see Note 1 below //cout<<s.append(t[1])<<endl; ​//an error; see Note 1 cout<<s.append(t.substr(1,1))<<endl; ​//prints eggplantak; see Note 1 cout<<s.find("gg")<<endl; if (s.find("gg")!=-1) cout<<"found...
In February 2012, the Pepsi Next product was launched into the US market. This case study...
In February 2012, the Pepsi Next product was launched into the US market. This case study provides students with an interesting insight into PepsiCo’s new product process and some of the challenging decisions that they faced along the way. Pepsi Next Case Study Introduction Pepsi Next was launched by PepsiCo into the US market in February 2012, and has since been rolled out to various international markets (for instance, it was launched in Australia in September 2012). The new product...
The Business Case for Agility “The battle is not always to the strongest, nor the race...
The Business Case for Agility “The battle is not always to the strongest, nor the race to the swiftest, but that’s the way to bet ’em!”  —C. Morgan Cofer In This Chapter This chapter discusses the business case for Agility, presenting six benefits for teams and the enterprise. It also describes a financial model that shows why incremental development works. Takeaways Agility is not just about the team. There are product-management, project-management, and technical issues beyond the team’s control. Lean-Agile provides...