Question

In the PowerPoint slides for lecture 15, you will find a function that performs binary search...

In the PowerPoint slides for lecture 15, you will find a function that performs binary
search on a Python list using recursion. Modify that binarySearchRec(alist,
item) function so that it performs ternary search on a Python list. Your new function
should find two midpoints that divide the list into three approximately equal size
segments. If the item being searched for is found at either of the midpoints, the function
should return True. If the item being searched for is less than the value at the first
midpoint, ternary search continues with the segment to the “left” of the first midpoint. If
the item being searched for is greater than the value at the second midpoint, ternary
search continues with the segment to the “right” of the second midpoint. Otherwise,
ternary search continues with the segment between the first and second midpoints. Name
your function ternarySearchRec.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Python Code:

def ternary_search (alist, item):
   # Initial values (List Boundaries)
   first = 0
   last = len(alist) - 1
   # Set found to false
   found = False
   # Iterate till first doesn't cross last and item not found
   while first <= last and not found:
       # First mid point
       mid1 = first + ((last - first) // 3)
       # Second mid point
       mid2 = first + (2 * ((last - first) // 3))
       # Comparing for item at starting
       if item == alist[first]:
           found = True
       # Comparing for item at ending
       elif item == alist[last]:
           found = False
       # Checking at edge values
       elif item < alist[first] or item > alist[last]:
           return False
       # Moving to first sub list
       elif item <= alist[mid1]:
           last = mid1
       # Moving to second sub list
       elif item > alist[mid1] and item <= alist[mid2]:
           first = mid1 + 1
           last = mid2
       else:
           first = mid2 + 1
   return found
  
  
def main():
   """ Main function """
   # List
   L = [1, 2, 3, 4, 5, 6, 7, 8]
  
   # Printing list
   print(L)
  
   # Checking function
   if ternary_search(L, 6):
       print("\nElement 6 found...\n")
   else:
       print("\nElement 6 not found...\n")
      
   if ternary_search(L, 22):
       print("\nElement 22 found...\n")
   else:
       print("\nElement 22 not found...\n")
  
  
# Calling main function
main()

_______________________________________________________________________________________________

Code Screenshot:

_______________________________________________________________________________________________

Sample Run:

Add a comment
Know the answer?
Add Answer to:
In the PowerPoint slides for lecture 15, you will find a function that performs binary search...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The binary search algorithm from Chapter 9 is a very efficient algorithm for searching an ordered...

    The binary search algorithm from Chapter 9 is a very efficient algorithm for searching an ordered list. The algorithm (in pseudocode) is as follows: highIndex - the maximum index of the part of the list being searched lowIndex - the minimum index of the part of the list being searched target -- the item being searched for //look in the middle middleIndex = (highIndex + lowIndex) / 2 if the list element at the middleIndex is the target return the...

  • Write a program (a3.py) that has 3 function definitions: magic-sequential(), magic-binary(), and main(). You will write...

    Write a program (a3.py) that has 3 function definitions: magic-sequential(), magic-binary(), and main(). You will write the code for the above functions. Both magic functions (magic-sequential() and magic-binary()) will look for a magic index in a given sorted list of distinct integers. A magic index in a list myList[0 ... n-1] is defined to be an index i such that myList[i] = i . Both functions receive the list as a parameter and return an integer: either the magic index,...

  • Python pls CENGAGE MINDTAP Q Search this course Programming Exercise 11.1 x Instructions search.py + >_...

    Python pls CENGAGE MINDTAP Q Search this course Programming Exercise 11.1 x Instructions search.py + >_ Terminal + A sequential search of a sorted list can halt when the target is less than a given element in the list. 1 " 2 File: search.py 3 Project 11.1 4 5 Optimizes sequential search for sorted lists. 6 The complexity is O(n) in the worst case and 0(1) in the best case. 7 The average case is less than n / 2,...

  • In this assignment you are asked to write a Python program to determine all the prime...

    In this assignment you are asked to write a Python program to determine all the prime numbers in between a range and store them in a list that will be printed when the range is searched. The user is prompted for two positive integer values as input, one is the start of the range and the other is the end of the range. If the user gives a negative value or enters a second number that is lower than the...

  • Python Problem: Variance Explanation: Problem 1: Computing variance For this problem, you will write a function...

    Python Problem: Variance Explanation: Problem 1: Computing variance For this problem, you will write a function variance that takes a list whose elements are numbers (floats or ints), and returns their variance, a single number. (If you don't remember how to compute variance, check the lecture notebook; it's one of the intermediate steps in computing standard deviation.) You should not use NumPy or any other Python libraries for this problem. For now, worry only about correctness, not efficiency. Passing an...

  • In Python! Search Exercise 11.A: Mergesort with a Comparator CS 1410 Background The sort algorithms we...

    In Python! Search Exercise 11.A: Mergesort with a Comparator CS 1410 Background The sort algorithms we have looked at in Module 8 have all sorted list elements in ascending because it compares elements with the less-than operator. For example, in our mergesort program, the comparison appears as follows: 18 L[1] R01 The effect of this comparison is that if L(i) is less than RC), then L[is considered to come before R[i] in the sorted result. Hence the ascending order of...

  • I need help writing this code in C++ Proj11.cpp is provided as well as the randomdata.txt thank you in advance! Objectives: The main objectives of this project is to introduce you to recursion,...

    I need help writing this code in C++ Proj11.cpp is provided as well as the randomdata.txt thank you in advance! Objectives: The main objectives of this project is to introduce you to recursion, and test your ability to work with some STL functionalities. A review of your knowledge on working with templates, dynamic data structures, as well as manipulating dynamic memory, classes, pointers and iostream to all extents, is also included. Description: For the entirety of this project, you will...

  • SELF-CHECK Why did the first version of method search that passed the first test itemNotFirstElementInSingleElementArray contain...

    SELF-CHECK Why did the first version of method search that passed the first test itemNotFirstElementInSingleElementArray contain only the statement return −1? Assume the first JUnit test for the findLargest method described in Self-Check exercise 2 in section 3.4 is a test that determines whether the first item in a one element array is the largest. What would be the minimal code for a method findLargest that passed this test? PROGRAMMING Write the findLargest method described in self-check exercise 2 in...

  • C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a...

    C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a structure called MyToDo to hold information about each todo item. The members of the MyToDo struct are description, due date, and priority. Each of these items will be stored in an array called ToDoList. The definition for the MyToDo struct should be placed in the header file called ToDo.h Visually think of the ToDoList like this: There are two ways to add items to...

  • You need not run Python programs on a computer in solving the following problems. Place your...

    You need not run Python programs on a computer in solving the following problems. Place your answers into separate "text" files using the names indicated on each problem. Please create your text files using the same text editor that you use for your .py files. Answer submitted in another file format such as .doc, .pages, .rtf, or.pdf will lose least one point per problem! [1] 3 points Use file math.txt What is the precise output from the following code? bar...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT