Question

In: Computer Science

Consider following Bisectional search implementation that prints the location of the elements found in a given...

Consider following Bisectional search implementation that prints the location of the elements found in a given sorted list. If not found it prints

-1. Modify the program such that it would provide:

• All the places in the list where the element was found

• How many times the element appeared in the list.

NOTE

Answer should be in python.

Solutions

Expert Solution

Ans: Both the sub-parts are solved using a single python program with binary search algorithm. Please read comments in the program to get a better understanding.

# Binary Search
def bisect(arr, key, getFirstOccurence):

    # Initial search area 
    low = 0 
    high = len(arr) - 1

        # Initialize the result by -1
    result = -1

    while low <= high:
        # Find the mid value in the search area
        mid = low + (high-low) // 2

        # If key is found, update the result
        if key == arr[mid]:
            result = mid

            # Search in the lower half to find first occurence
            if getFirstOccurence:
                high = mid - 1
            # Search in the upper half to find last occurence
            else:
                low = mid + 1

        # If key is less than the middle element, search in lower half
        elif key < arr[mid]:
            high = mid - 1
        # If key is more than the middle element, search in upper half
        else:
            low = mid + 1

    # Return the index if found or -1 if the element is not found
    return result


# Driver function
if __name__ == '__main__':

    arr = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9]
    key = int(input())

    first = bisect(arr, key, True)  # True to find first occurrence
    last = bisect(arr, key, False)  # False to find last occurrence

    count = last-first+1

    if first != -1:

        # 0-based indexes
        print("1. All Occurences:", end = " ")
        while first<=last:
            print(str(first), end = " ")
            first += 1

        # Printing count in a new line
        print()
        print("2. Count: "+str(count))

    else:
        # Print -1 if not found
        print(str(-1))

Related Solutions

Consider following Bisectional search implementation that prints the location of the elements found in a given...
Consider following Bisectional search implementation that prints the location of the elements found in a given sorted list. If not found it prints -1. Modify the program such that it would provide: • All the places in the list where the element was found • How many times the element appeared in the list. #Bisectional search (return one of the locations) def bisectioanl_search(L,k, low, high): if high>=low: mid = (low + high) // 2 if L[mid]==k: return mid elif L[mid]>k:...
In C++ Consider the binary search tree implementation in file bintree.cp a)Add to the TreeNode class...
In C++ Consider the binary search tree implementation in file bintree.cp a)Add to the TreeNode class a pointer to the parent node. Modify the insert and erase functions to properly set those pointers. b)Then define a TreeIterator class that contains a pointer to a TreeNode and has member functions get and next. i)The iterator’s get member function should return the data value of the node to which it points. ii)The iterator’s next member function should find the next element in...
Write a pseudocode or java code implementation for linear search that searches elements based on a key value from an array of undetermined length
Write a pseudocode or java code implementation for linear search that searches elements based on a key value from an array of undetermined lengthJAVA
Given a binary search tree T with n elements. For any two keys k1 and k2...
Given a binary search tree T with n elements. For any two keys k1 and k2 such that k1 < k2, there is an algorithm to print all elements x in T such that k1 ≤x ≤k2 in O(K + log n) time on average, where K is the number of the elements printed out.
Given a binary search tree T with n elements. For any two keys k1 and k2...
Given a binary search tree T with n elements. For any two keys k1 and k2 such that k1 < k2, there is an algorithm to print all elements x in T such that k1 ≤x ≤k2 in O(K + log n) time on average, where K is the number of the elements printed out.
Why are the most abundant elements found in our bodies not the most abundant elements found...
Why are the most abundant elements found in our bodies not the most abundant elements found in Earth's crust? (e.g., What characteristics of the most abundant elements in our bodies make them suitable for life?) How do the structures of carbohydrates, lipids, proteins (structural and enzymatic), and nucleic acids relate to their functions? Include in your discussion a brief description of the structure of each type of molecule.
Consider a simple economy with search and unemployment. The matching function is given by: M =...
Consider a simple economy with search and unemployment. The matching function is given by: M = em(Q, A) = eQ^(3/5)A^(2/5) where the government supplied employment insurance is b = 0.5, the worker productivity is z = 1.3, firms’ cost of posting a vacancy is k = 0.1, the matching efficiency parameter is e = 0.4191 and the worker’s bargaining power factor is a = 0.5. The working-age population is N = 1000 and we denote by Q the labor force....
Consider the dissociaton of methane, into the elements H2g and C(s) given a) the change of...
Consider the dissociaton of methane, into the elements H2g and C(s) given a) the change of enthalpy of reaction is -74.85 kJ/mol and change of entropyof reaction is -80.67 J/mol K at 298K. Calculate the Keq at 298K. b) Assuming that change in enthalpy of formation is independent of temperature, calculate K at 323K. c) Calculate the degree of dissociation of methane at 298K and Ptotal at 0.01 bar.
Given the following array of 8 elements, show the steps to sortthe elements in ascending...
Given the following array of 8 elements, show the steps to sort the elements in ascending order using a radix sort. Fill in each of the following blanks.81   546   677   9   97   12   53   22Adjust with 0s:Buckets for ones digit:Buckets for tens digit:Final Result:
(C++) Write a program that prints a table in the following format given a "x" read...
(C++) Write a program that prints a table in the following format given a "x" read from the keyboard. For example, if x is 4, it prints out 0 0 1 1 2 4 3 9 4 16 To avoid mismatch, put 8 white spaces between two numbers.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT