Question

In: Computer Science

ASAP Use python please!! Write a program including   binary-search and merge-sort in Python. You also need to  modify...

ASAP Use python please!!

Write a program including   binary-search and merge-sort in Python.

You also need to  modify the code posted and use your variable names and testArrays.  

Solutions

Expert Solution

Binary Search - Example

Binary Search works on a divide-and-conquer approach and relies on the fact that the array is sorted to eliminate half of possible candidates in each iteration. More specifically, it compares the middle element of the sorted array to the element it's searching for in order to decide where to continue the search.

If the target element is larger than the middle element - it can't be located in the first half of the collection so it's discarded. The same goes the other way around.

Note: If the array has an even number of elements, it doesn't matter which of the two "middle" elements we use to begin with.

Let's look at an example quickly before we continue to explain how binary search works:

As we can see, we know for sure that, since the array is sorted, x is not in the first half of the original array.

When we know in which half of the original array x is, we can repeat this exact process with that half and split it into halves again, discarding the half that surely doesn't contain x:

We repeat this process until we end up with a subarray that contains only one element. We check whether that element is x. If it is - we found x, if it isn't - x doesn't exist in the array at all.

If you take a closer look at this, you can notice that in the worst-case scenario (x not existing in the array), we need to check a much smaller number of elements than we'd need to in an unsorted array - which would require something more along the lines of Linear Search, which is insanely inefficient.

To be more precise, the number of elements we need to check in the worst case is log2N where N is the number of elements in the array.

This makes a bigger impact the bigger the array is:

Binary Search Implementation

Binary Search is a naturally recursive algorithm, since the same process is repeated on smaller and smaller arrays until an array of size 1 has been found. However, there is of course an iterative implementation as well, and we will be showing both approaches.

Recursive

Let's start off with the recursive implementation as it's more natural:

def binary_search_recursive(array, element, start, end):

if start > end:

return -1

mid = (start + end) // 2

if element == array[mid]:

return mid

if element < array[mid]:

return binary_search_recursive(array, element, start, mid-1)

else:

return binary_search_recursive(array, element, mid+1, end)

Let's take a closer look at this code. We exit the recursion if the start element is higher than the end element:

if start > end:
        return -1

This is because this situation occurs only when the element doesn't exist in the array. What happens is that we end up with only one element in the current sub-array, and that element doesn't match the one we're looking for.

At this point, start is equal to end. However, since element isn't equal to array[mid], we "split" the array again in such a way that we either decrease end by 1, or increase start by one, and the recursion exists on that condition.

We could have done this using a different approach:

if len(array) == 1:

if element == array[mid]:

return mid

else:

return -1

The rest of the code does the "check middle element, continue search in the appropriate half of the array" logic. We find the index of the middle element and check whether the element we're searching for matches it:

mid = (start + end) // 2
if elem == array[mid]:
    return mid

If it doesn't, we check whether the element is smaller or larger than the middle element:

if element < array[mid]:
    # Continue the search in the left half
    return binary_search_recursive(array, element, start, mid-1)
else:
    # Continue the search in the right half
    return binary_search_recursive(array, element, mid+1, end)

Let's go ahead and run this algorithm, with a slight modification so that it prints out which subarray it's working on currently:

element = 18
array = [1, 2, 5, 7, 13, 15, 16, 18, 24, 28, 29]

print("Searching for {}".format(element))
print("Index of {}: {}".format(element, binary_search_recursive(array, element, 0, len(array))))

Running this code will result in:

Searching for 18
Subarray in step 0:[1, 2, 5, 7, 13, 15, 16, 18, 24, 28, 29]
Subarray in step 1:[16, 18, 24, 28, 29]
Subarray in step 2:[16, 18]
Subarray in step 3:[18]
Index of 18: 7

It's clear to see how it halves the search space in each iteration, getting closer and closer to the element we're looking for. If we tried searching for an element that doesn't exist in the array, the output would be:

Searching for 20
Subarray in step 0: [4, 14, 16, 17, 19, 21, 24, 28, 30, 35, 36, 38, 39, 40, 41, 43]
Subarray in step 1: [4, 14, 16, 17, 19, 21, 24, 28]
Subarray in step 2: [19, 21, 24, 28]
Subarray in step 3: [19]
Index of 20: -1

Related Solutions

ASAP! write a program including   binary-search and merge-sort in Python. You also need to  modify the code posted...
ASAP! write a program including   binary-search and merge-sort in Python. You also need to  modify the code posted and use your variable names and testArrays.  
Write a program including  binary-search and merge-sort in Python. it has to output the following: NeArr range(0,...
Write a program including  binary-search and merge-sort in Python. it has to output the following: NeArr range(0, 20)                                                                                                           result for searching 6 True                                                                                                  result for searching 16 False                                                                                                                              for-loop's function                                                                                                          arr range(0, 15)                                                                                                             for-loop's func result for searching 6 1                                                                                     result for searching 16 0 it has to be a simple code and please!! put the whole code together.
Write a JAVA program to modify the insert and remove of a binary search tree to...
Write a JAVA program to modify the insert and remove of a binary search tree to become an AVL tree.
C++ ONLY Binary Search and Selection Sort A binary search first requires a sort. Use a...
C++ ONLY Binary Search and Selection Sort A binary search first requires a sort. Use a selection sort to organize an array, then find the value using a binary search. Input the array, and a value to find. Output the sorted array and the value if contained in the array. /* * File: main.cpp * Author: * Created on: * Purpose: Binary Search */ //System Libraries #include <iostream> //Input/Output Library #include <cstdlib> //Random Functions #include <ctime> //Time Library using namespace...
This question has three parts: a) binary search, b) selection sort, and c) merge sort. a)...
This question has three parts: a) binary search, b) selection sort, and c) merge sort. a) Suppose we are performing a binary search on a sorted list called numbers initialized as follows: #index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 numbers = [-2, 0, 1, 7, 9, 16, 19, 28, 31, 40, 52, 68, 85, 99] #search for the value 5 index = binary_search(numbers, 5) Write the indexes of the elements that would...
Assume you need to write a Java program that uses a binary search algorithm to search...
Assume you need to write a Java program that uses a binary search algorithm to search a sorted array for a given value. 1. Write a Java pseudocode that uses recursion to accomplish the task. Here is a hint. When you are searching for a particular value in an array, there are two possible outcomes. 1) The value is found and the array index of that value is returned. 2) The value is not found and we return -1. (5...
NEED: INSERTION SORT AND BINARY SEARCH IMMEDIATE NEED: Implement 2 searches and 2 sorts, and write...
NEED: INSERTION SORT AND BINARY SEARCH IMMEDIATE NEED: Implement 2 searches and 2 sorts, and write test programs to convince someone that you did them right. DIRECTIONS: You have been provided: 1. Function stubs for searching and sorting algorithms: Utility functions: swap, shift right/left, show array, insertion point. Searching: linear seach, binary search Sorting: bubble sort, insertion sort, selection sort. 2. Main program providing a pattern for testing youour functions, including: - sample arrays, each providing a different test case....
Write a program in Java to sort the given array using merge sort, quick sort, insertion...
Write a program in Java to sort the given array using merge sort, quick sort, insertion sort, selection sort and bubble sort based on the input from the user which sorting technique they wanted to use. Get the array size, array elements from the user, and also display the sorted array along with the name of the sorting technique used.
Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort I need it in Java with...
Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort I need it in Java with comments and I need the input file to be placed with Scanner not BufferedReader Please help I need Class River Class CTRiver and Class Driver Class River describes river’s name and its length in miles. It provides accessor methods (getters) for both variables, toString() method that returns String representation of the river, and method isLong() that returns true if river is above 30 miles...
Need in JAVA. You are to use Binary Trees to do this Program. Write a complete...
Need in JAVA. You are to use Binary Trees to do this Program. Write a complete program, which will process several sets of numbers: For each set of numbers you should: 1. Create a binary tree. 2. Print the tree using “inorder”, “preorder”, and “postorder”. 3. Call a method Count which counts the number of nodes in the tree. 4. Call a method Children which prints the number of children each node has. 5. Inset and delete several nodes according...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT