Python Binary Search Algorithm Visualizer Project

Rahul Patodi
DataFlair
Published in
6 min readMar 19, 2024

The “Binary Search Algorithm Visualizer” project aims to provide a user-friendly interface for visualizing the Binary Search Algorithm in action.

This Python Project allows users to input a sorted list of numbers and a target number to search for. The Binary Search Algorithm is then applied to the input list to determine if the target number exists in the list and, if so, at which index.

The GUI (Graphical User Interface) is designed to be intuitive, with a green color scheme and a prominent pink search button. The result of the search is displayed in pink text below the button, providing users with immediate feedback on the outcome of their search.

This Python Binary Search Algorithm Visualizer project serves as an educational tool for understanding and demonstrating the efficiency of the Binary Search Algorithm.

Binary Search Algorithm Visualizer in Python
Binary Search Algorithm Visualizer in Python

About Python Binary Search Algorithm Visualizer

The “Binary Search Algorithm Visualizer” project is designed to provide a user-friendly interface for visualizing the Binary Search Algorithm in action. Users can input a sorted list of numbers and a target number to search for, and the algorithm will efficiently determine if the target number exists in the list and, if so, at which index.

The GUI features a green color scheme with a prominent pink search button, enhancing the user experience.

This Python Project serves as an educational tool for understanding and demonstrating the efficiency of the Binary Search Algorithm, making it accessible and informative for users of all levels.

Prerequisites For Python Binary Search Algorithm Visualizer

  • Tkinter: Tkinter is Python’s standard GUI (Graphical User Interface) toolkit. It should be included with most Python installations. If not, you can install it using the following command:
pip install tk
  • IDE (Integrated Development Environment): Choose an IDE for Python development. Popular options include PyCharm, Visual Studio Code, and IDLE (included with Python).
  • Basic Python Knowledge: Understanding of basic Python programming concepts such as variables, loops, functions, and lists is essential for this project.

Python Binary Search Algorithm Visualizer File Structure

1. GUI Creation: Use Tkinter to create a graphical user interface (GUI) that allows users to input a sorted list of numbers and a target number to search for. Include labels, entry fields, and a button for the search operation.

2. Binary Search Algorithm Implementation: Write a function to implement the Binary Search Algorithm. This function will take the sorted list and the target number as input and return the index of the target number in the list if found, or -1 if not found.

3. Search Functionality: Implement a search function that parses the input from the GUI, calls the Binary Search Algorithm function, and updates the GUI with the search result.

4. Result Display: Add a label below the search button to display the result of the search. Update the label text to indicate whether the target number was found or not, along with the index if found.

5. Error Handling: Include error handling to manage invalid inputs, such as non-numeric characters or empty input fields. Display error messages in a pop-up dialog box to alert the user.

Python Binary Search Algorithm Visualizer Implementation

Step 1: Import Necessary Libraries

First, import the required libraries, including Tkinter for the GUI and messagebox for displaying messages.

import tkinter as tk
from tkinter import messagebox

Step 2: Implement the Binary Search Algorithm

A function to implement the Binary Search Algorithm, which takes a sorted list and a target number as input and returns the index of the target number in the list, or -1 if the target number is not found.

def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
  • Initialization: The algorithm starts by setting `low` to the first index of the array (`0`) and `high` to the last index of the array (`len(arr) — 1`). It then enters a loop that continues as long as `low` is less than or equal to `high`.
  • Finding the Middle: Inside the loop, it calculates the `mid` index as the average of `low` and `high`. It then checks if the element at the `mid` index is equal to the target. If it is, the function returns the `mid` index, indicating that the target has been found.
  • Adjusting the Range: If the element at the `mid` index is less than the target, it means the target is in the right half of the remaining array. So, it updates `low` to `mid + 1` to search in the right half. If the element at the `mid` index is greater than the target, it updates `high` to `mid — 1` to search in the left half. This process continues until the target is found or the `low` index is greater than the `high` index, indicating that the target is not in the array. If the target is not found after the loop, the function returns `-1`.

Step 3: Create the GUI

# GUI
root = tk.Tk()
root.title("Flood-Binary Search Algorithm")
root.configure(bg="green")
  • tk.Tk(): Creates the main application window.
  • root.title(): Sets the title of the window.
  • root.configure(): Configures the background color of the window.

Step 4: Add Labels and Entry Fields

label_numbers = tk.Label(root, text="Enter sorted numbers (separated by space):", bg="green", fg="white")
label_numbers.pack()


entry_numbers = tk.Entry(root, width=70)
entry_numbers.pack()


label_target = tk.Label(root, text="Enter target number:", bg="green", fg="white")
label_target.pack()


entry_target = tk.Entry(root, width=50)
entry_target.pack()
  • tk.Label(): Creates a label widget for displaying text.
  • tk.Entry(): Creates an entry widget for user input.

Step 5: Add Result Label

search_button = tk.Button(root, text="Search", command=search, bg="pink")
search_button.pack()
  • result_label: Creates a label widget to display the search result.

Step 6: Define the Search Function

def search():
try:
target = int(entry_target.get())
numbers = list(map(int, entry_numbers.get().split()))
numbers.sort()
index = binary_search(numbers, target)
if index != -1:
result_label.config(text=f"Target found at index {index}.", fg="black")
else:
result_label.config(text="Target not found.", fg="pink")
except ValueError:
messagebox.showerror("Error", "Invalid input. Please enter valid numbers.")
  • search(): This function is called when the user clicks the search button. It retrieves the target number and the list of numbers from the entry fields, sorts the list, calls the binary_search function to find the target number, and updates the result_label with the outcome.

Step 7: Run the Application

Finally, run the application by calling `root.mainloop()`. This will start the GUI and allow users to interact with the Binary Search Algorithm Visualizer.

root.mainloop()

Python Binary Search Algorithm Visualizer Code

import tkinter as tk
from tkinter import messagebox


def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1


def search():
try:
target = int(entry_target.get())
numbers = list(map(int, entry_numbers.get().split()))
numbers.sort()
index = binary_search(numbers, target)
if index != -1:
result_label.config(text=f"Target found at index {index}.", fg="black")
else:
result_label.config(text="Target not found.", fg="pink")
except ValueError:
messagebox.showerror("Error", "Invalid input. Please enter valid numbers.")


# GUI
root = tk.Tk()
root.title("Flood-Binary Search Algorithm")
root.configure(bg="green")


label_numbers = tk.Label(root, text="Enter sorted numbers (separated by space):", bg="green", fg="white")
label_numbers.pack()


entry_numbers = tk.Entry(root, width=70)
entry_numbers.pack()


label_target = tk.Label(root, text="Enter target number:", bg="green", fg="white")
label_target.pack()


entry_target = tk.Entry(root, width=50)
entry_target.pack()


search_button = tk.Button(root, text="Search", command=search, bg="pink")
search_button.pack()


result_label = tk.Label(root, text="", bg="green")
result_label.pack()


root.mainloop()

Python Binary Search Algorithm Visualizer Output

Python Binary Search Algorithm Visualizer Output
Python Binary Search Algorithm Visualizer Output
Python Binary Search Algorithm Visualizer
Python Binary Search Algorithm Visualizer
Binary Search Algorithm Visualizer in Python Output
Binary Search Algorithm Visualizer in Python

Conclusion

The “Binary Search Algorithm Visualizer” project offers an interactive platform for users to explore and understand the Binary Search Algorithm. By providing a simple and intuitive graphical interface, users can input a sorted list of numbers and a target number, and observe how the algorithm efficiently locates the target within the list.

The project serves as a learning tool for beginners to grasp the concept of binary search and provides a practical demonstration of its effectiveness in real time.

Through its user-friendly design and visual representation of the algorithm’s operation, the project aims to make learning and understanding the Binary Search Algorithm engaging and accessible to users of all levels.

--

--