Python2.Word
Python2.Word
PROJECT
REPORT ON
“ Binary Search in Python”
SUBMITTED BY
Mst. Londhe Mahesh Raghunath(143)
Under The Guidance Of
Prof.M.V.KHASNE
1
Sanjivani Rural Education Society’s
SANJIVANI K.B.P. POLYTECHNIC
Department of Computer Technology
SUBMITTED BY
Mst. Londhe Mahesh Raghunath(143)
Under our supervision and guidance for partial fulfilment of the requirement for
2
Content
i. Introduction
ii. Types
iii. Advantages
iv. Disadvantages
v. Algorithm
vi. Project Details
vii. Project Prerequisites
viii. Steps to create Binary Search Algorithm
Project in Python
ix. Program
x. Output (Result)
xi. Conclusion
xii. Reference
3
Introduction
Binary search is a fundamental algorithm used to efficiently
locate a target value within a sorted sequence of elements. It
operates by repeatedly dividing the search interval in half
until the target element is found or the interval is empty. This
approach contrasts with linear search, which traverses the
sequence sequentially. Binary search is particularly useful
when dealing with large datasets, as it dramatically reduces
the number of comparisons required to find an element.
In Python, binary search can be implemented using either
iterative or recursive approaches.
Types
1. Iterative Binary Search:
- In iterative binary search, the search process is carried
out using loops, typically a while loop.
- The algorithm repeatedly divides the search interval in
half, narrowing down the range of possible positions for the
target element.
- At each iteration, it compares the target element with the
middle element of the current interval and adjusts the search
interval accordingly.
- This process continues until the target element is found, or
the search interval becomes empty, indicating that the target
element is not present in the sequence.
4
2. Recursive Binary Search:
- Recursive binary search employs a recursive function to
perform the search operation.
- Similar to the iterative approach, it divides the search
interval in half and recursively applies the search algorithm
to the appropriate subinterval.
- The base case of the recursion occurs when the search
interval becomes empty, signalling that the target element is
not present.
- Recursive binary search typically requires less code
compared to its iterative counterpart and may be more
intuitive for some programmers.
- However, excessive recursion can lead to stack overflow
errors, especially for large datasets, so care must be taken
when using this approach.
5
Advantages
1. Efficient for Sorted Data: Binary search is highly
efficient for searching in sorted data. It significantly
reduces the search space by half in each iteration,
making it particularly suitable for large datasets where
linear search would be impractical.
2. Logarithmic Time Complexity: Binary search has a
time complexity of O (log n), where n is the number of
elements in the sorted sequence. This logarithmic time
complexity means that even for large datasets, binary
search can quickly locate the target element.
3. Versatility: Binary search can be applied to various
types of sorted data structures, including arrays, lists,
and trees. Its versatility allows it to be used in a wide
range of applications, from searching in databases to
implementing efficient algorithms in computer science.
4. Minimal Space Complexity: Binary search typically
requires minimal additional memory overhead, as it
operates directly on the existing sorted data structure.
This makes it suitable for memory-constrained
environments and applications where space efficiency is
crucial.
5. Deterministic Behaviour: Binary search exhibits
deterministic behaviour, meaning that for a given sorted
dataset and target element, it will always produce the
same result. This predictability makes it reliable for use
in critical systems and applications.
6
Disadvantages
1. Requirement of Sorted Data: Binary search requires
the data to be sorted before performing the search
operation. If the data is not sorted or if it frequently
changes, the overhead of maintaining sorted order may
outweigh the benefits of binary search.
2. Inapplicability to Unsorted Data: Unlike linear
search, which can operate on unsorted data, binary
search cannot be directly applied to unsorted data.
Sorting the data before performing binary search incurs
an additional time complexity of O (n log n), which may
be prohibitive in some cases.
3. Limited to Single-Dimensional Data: Binary search is
most suitable for searching in single-dimensional sorted
sequences, such as arrays or lists. It cannot be directly
applied to multidimensional data structures without
appropriate preprocessing or modifications.
4. Lack of Dynamic Updates: Binary search is not well-
suited for applications that require frequent updates to
the dataset, such as dynamic databases or real-time
systems. Whenever the data changes, the sorted order
must be maintained, which can be inefficient or
impractical in certain scenarios.
5. Potential for Integer Overflow: In languages with
fixed-size integer types, such as Python's int type, binary
search may be susceptible to integer overflow issues
when dealing with extremely large datasets. Care must
be taken to handle overflow situations to ensure correct
behaviour.
7
Algorithm
The algorithm for Iterative Approach is –
def binary_search(n, item):
left, right= 0, len(n)
while right > left:
middle = (left + right) // 2
if nums[middle] > item:
right = middle
elif nums[middle] < item :
left = middle + 1
else:
return middle
return None
Project Details
We are going to create a project and test it using the same entries in
the example. In this project we will just be making use of Tkinter
Module to create a GUI using python. We will take the input of the
number from the user.
In the project, we are going to use the iterative approach.
8
Project Prerequisites
To build this project we need to build a basic understanding of python
concepts like loops. To create the GUI we need to install the Tkinter
Module. Following is the command to install the Tkinter Module-
pip3 install tk
def binary_search():
def binary_search():
l = e.get().split(" ")
for i in range(0, len(l)):
l[i] = int(l[i])
num = n.get()
first = 0
9
last = len(l) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
if l[mid] == num:
found = True
else:
if num < l[mid]:
last = mid - 1
else:
first = mid + 1
if found == True:
Label(window, text="Number found in the list",
font=('Calibri')).place(x=280, y=180)
else:
Label(window, text="Number NOT found in the list",
font=('Calibri')).place(x=240, y=210)
10
Label(window, text="Enter number you want to search",
font=('Calibri')).pack()
e = Entry(window)
e.pack()
n = IntVar()
Entry(window, textvariable=n).place(x=280, y=110)
Button(window, text="Search",
command=binary_search).place(x=320, y=160)
window.mainloop()
n=IntVar()
window.mainloop()#main command
To display the window that we have created, we use the
mainloop(). Without this function, the window will not be
displayed.
11
Program
import tkinter as tk
from tkinter import messagebox
def binary_search():
num_to_find = n.get()
try:
search_num = int(num_to_find)
input_list_str = e.get()
if not input_list_str:
result_label.config(text="Please enter numbers.")
return
try:
sorted_list = [int(x) for x in input_list_str.split()]
sorted_list.sort() # Ensure list is sorted for binary search
except ValueError:
result_label.config(text="Invalid input in the list. Please enter
numbers separated by space.")
return
first = 0
last = len(sorted_list) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
if sorted_list[mid] == search_num:
found = True
else:
if search_num < sorted_list[mid]:
last = mid - 1
else:
first = mid + 1
if found:
result_label.config(text=f"Number {search_num} found in the
list at index {mid}")
else:
result_label.config(text=f"Number {search_num} NOT found
12
in the list")
except ValueError:
result_label.config(text="Invalid input for the number to
search.")
window = tk.Tk()
window.geometry("700x350")
window.title("Binary Search")
e = tk.Entry(window)
e.pack()
n = tk.StringVar()
search_num_entry = tk.Entry(window, textvariable=n)
search_num_entry.pack()
window.mainloop()
13
Output (Result)
14
Conclusion
Binary search is a powerful algorithm for efficiently searching
for a target element within a sorted sequence. Its logarithmic
time complexity makes it highly efficient, especially for large
datasets, as it dramatically reduces the search space with each
iteration. Through this guide, we have explored the
implementation of binary search in Python, covering both
iterative and recursive approaches.
By understanding the principles behind binary search and its
Python implementation, you can leverage its advantages in
various programming scenarios. Whether you're working with
arrays, lists, or other sorted data structures, binary search
offers a reliable and efficient solution for locating elements.
However, it's essential to consider the limitations of binary
search, such as its requirement for sorted data and its inability
to handle unsorted or dynamically changing datasets
efficiently. Additionally, while binary search excels in single-
dimensional sorted sequences, it may not be directly applicable
to multidimensional data structures without appropriate
modifications.
Overall, mastering binary search in Python equips you with a
valuable tool for optimizing search operations in your
programs and solving a wide range of problems more
efficiently. Whether you're developing algorithms, working
with databases, or building user interfaces, binary search can
help you achieve faster and more reliable results.
15
Reference
Ravi Majithia, Programming with Python (4th Edition),
TechKnowledge Publication
https://www.pythongeeks.org/python-binary-search/
https://www.freecodecamp.org/news/binary-search-in-python-
with-examples/
https://realpython.com/lessons/search-algorithms/
https://stackabuse.com/binary-search-in-python/
https://pythonguides.com/python-binary-search/
www.google.com
www.wikipedia.com
16