Python Forum
Basic binary search algorithm - using a while loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic binary search algorithm - using a while loop
#1
I’m learning algorithms using Python. My latest challenge laid out by the instructor in my highly sophisticated non-accredited Udemy course content I am watching is to write a basic binary search algorithm.

Here is the pseudo code:

Quote:This function accepts a sorted array and a value
Create a left pointer at the start of the array, and a right pointer at the end of the array
While the left pointer comes before the right pointer
Create a pointer in the middle
If you find the value you want, return the index pointer
If the value is too small, move the left pointer down
If the value is too large, move the right pointer up
Else return not present

This is the implementation I came up with:

def binary_seek(array,target):
   start = 0
   end = array[-1]
   middle = (start + end) // 2
   print(f'Initialization: {start}, {middle}, {end}')
   while (array[middle] != target) and (start <= end):
       print(start, middle, end)
       if target < array[middle]:
           print(start, middle, end)
           end = middle -1
           middle = (start + end) // 2
           print(start, middle, end)
       else:
           print(start, middle, end)
           start = middle + 1
           middle = (start + end) // 2           
           print(start, middle, end)
   if array[middle] == target:
       print(start, middle, end)
       return print(f'Found:{middle}')
   else:
       print(start, middle, end)
       return print(f'Not Found')
When I run: print(binary_seek([ 1, 3, 4, 6, 8, 9, 11, 12, 15, 16, 17, 18, 19 ],6)) - - that returns: “Found: 3”. So this works.

But when I proceed to search for the value of 18 (with an index position to the right of the middle of the original array), Python throws an “index out of range” error and I am not sure why. For example, this is the output when trying to search for 18:

Quote:Initialization: 0, 9, 19
0 9 19
0 9 19
10 14 19
Traceback (most recent call last):
File “/<location>/algos/basic_binary_search/bbs5.py”, line 26, in
print(binary_seek([ 1, 3, 4, 6, 8, 9, 11, 12, 15, 16, 17, 18, 19 ],18))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/<location>/algos/basic_binary_search/bbs5.py”, line 6, in binary_seek
while (array[middle] != element) and (start <= end):
~~~~~^^^^^^^^
IndexError: list index out of range

It breaks before the second iteration of the while loop can execute.

The while loop on its first iteration traverses to the if conditional and since the target is not less than the middle of the array, Python proceeds down to the else operation and on its first pass there successfully repositions the start value to the old middle (10), re-calculates and assigns the new middle (to 14), and the end value remains (19). Since the middle value (10) is not the target, the while loop should run again. But Python chokes there with that “list index out of range” error.

What might you people suggest I try next? Comments? Feedback and tips welcome.
Reply
#2
Why this?
start = 0
end = array[-1]
If start is an index, why is end an array value?

Quote:that returns: “Found: 3. So this works
Returning the correct result for 1 test only means it returns a correct result for one test. It doesn't mean it works. The correct result could be returned for a reason having nothing to do with the correct implementation of the algorithm or the correctness of the algorithm. Testing your code with [1, 3, 4, 6, 8, 9, 11, 12, 15, 16, 17, 18, 19] raises an IndexError for any target > 16. I wouldn't describe that as "works".

Testing tries to find ways that the algorithm fails. If any test finds a fail, it means the algorithm has an error. If all tests pass it only means you didn't write a test that makes the algorithm fail. Unless you can test all possible cases, testing cannot prove that an algorithm works

Your function is useless. It returns None if it finds the target and None if it doesn't. It should return the index of the value or None if the value is not found. Your function should not print any output.

Convention is to have tabs be 4 spaces, not 3.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing a Linear Search algorithm - malformed string representation Drone4four 10 963 Jan-10-2024, 08:39 AM
Last Post: gulshan212
  Replace for loop to search index position illmattic 5 1,285 Sep-03-2022, 04:04 PM
Last Post: illmattic
  search binary file and list all founded keyword offset Pyguys 4 2,787 Mar-17-2020, 06:46 AM
Last Post: Pyguys
  understanding basic loop behaviour vinci 5 2,918 Feb-11-2020, 09:53 PM
Last Post: vinci
  hex file to binary or pcap to binary baran01 1 5,706 Dec-11-2019, 10:19 PM
Last Post: Larz60+
  basic binary search deep_logic 4 2,451 Sep-28-2019, 03:39 PM
Last Post: newbieAuggie2019
  Basic Python 3 Win 10 Search Txt to File Newbie SnakeTyro 6 150,902 Apr-18-2019, 09:36 PM
Last Post: SnakeTyro
  How can I make a faster search algorithm pianistseb 19 6,603 Apr-18-2019, 05:48 PM
Last Post: Larz60+
  binary search string help kietrichards 1 2,215 Mar-08-2019, 12:43 PM
Last Post: stullis
  Shanting Yard Algorithm basic implementation praevalens 1 2,217 Aug-29-2018, 01:05 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020