0% found this document useful (0 votes)
2 views

Python2.Word

This document is a project report on implementing Binary Search in Python, detailing both iterative and recursive approaches. It covers the advantages and disadvantages of binary search, provides algorithms for both methods, and outlines a project using Tkinter for a graphical user interface. The report concludes by emphasizing the efficiency of binary search for sorted data and its applicability in various programming scenarios.

Uploaded by

ophi55566
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python2.Word

This document is a project report on implementing Binary Search in Python, detailing both iterative and recursive approaches. It covers the advantages and disadvantages of binary search, provides algorithms for both methods, and outlines a project using Tkinter for a graphical user interface. The report concludes by emphasizing the efficiency of binary search for sorted data and its applicability in various programming scenarios.

Uploaded by

ophi55566
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

A MICRO

PROJECT
REPORT ON
“ Binary Search in Python”
SUBMITTED BY
Mst. Londhe Mahesh Raghunath(143)
Under The Guidance Of
Prof.M.V.KHASNE

Department Of Computer Technology

Sanjivani Rural Education Society’s

SANJIVANI K.B.P. POLYTECHNIC


KOPARGAON – 423603, Dist- Ahmednagar
2024-2025

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

DIPLOMA IN COMPUTER TECHNOLOGY affiliated


to Maharashtra State Board of Technical Education,
Mumbai For academic year
2024-2025

Subject Teacher HOD


Prof. M.V.KHASNE Mr.G.N.JORVEKAR

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.

Both iterative and recursive binary search algorithms have


their advantages and are suited to different programming
scenarios. Iterative binary search is often preferred for its
simplicity and efficiency, particularly when dealing with large
datasets, while recursive binary search may offer a more
elegant solution in certain contexts.

Understanding the characteristics and implementation details


of both types of binary search can empower you to choose the
most appropriate approach based on the specific
requirements of your Python projects.

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

The algorithm for Recursive Approach is –


def binary_search(n, item, start, end):
middle = (start + end) // 2
if start == end:
return None
if n[middle] > item:
return binary_search(n, item, start, middle)
elif nums[middle] < item:
return binary_search(n, item, middle + 1, end)
else:
return middle

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

Steps To Create the Binary Search Algorithm


Project in Python
Following are steps to create a Binary Search Algorithm Project.
1. Import the Required Modules
2. Creating the Binary Search Algorithm
3. Creating the GUI

1. Import the Required Modules:


import tkinter as tk

 Tkinter Module – To create a GUI in Python. Here we are using


alias tk so that referring to the module is easier during the
execution of the project.

2. Creating the Binary Search Algorithm:


 To implement the binary search algorithm, we have created a
function named binary_search()

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)

 This function ‘binary_search()’ performed the binary search


algorithm.
 It retrieves the input list from the entry field ‘e’ and converts it
into a list of integers.
 It retrieves the search number from the entry field ‘n’.
 The binary search algorithm is then executed on the list to find
the search number.
 Depending on whether the number is found or not it updates
GUI with appropriate labels.

3. Creating the GUI:


window = Tk()
window.geometry("700x350")
window.title("Binary Search")

head = Label(window, text="Let's perform Binary Search",


font=('Calibri 15'))
head.pack(pady=20)

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()

 Here, a Tkinter window is created with specify dimension and a


title.
 Labels are added to display instructions and message to the user.
 Entry fields are provided for entering the list of numbers (‘e’)
and the search number (‘n’).
 The button labeled “Search” is created which when clicked
triggered the ‘binary_search()’ function.

n=IntVar()

 To make sure the entered text is a number we use the IntVar()


method.

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")

head = tk.Label(window, text="Let's perform Binary Search",


font=('Calibri 15'))
head.pack(pady=20)

search_label = tk.Label(window, text="Enter numbers separated by


space:")
search_label.pack()

e = tk.Entry(window)
e.pack()

search_num_label = tk.Label(window, text="Enter number you want


to search:")
search_num_label.pack()

n = tk.StringVar()
search_num_entry = tk.Entry(window, textvariable=n)
search_num_entry.pack()

search_button = tk.Button(window, text="Search",


command=binary_search)
search_button.pack()

result_label = tk.Label(window, text="")


result_label.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

You might also like