- Python Basic Programs
- Python Program Examples
- Python Print Hello World
- Python Get Input from User
- Python Add Two Numbers
- Add Subtract Multiply Divide
- Python Check Even or Odd
- Python Check Prime or Not
- Python Check Alphabet or Not
- Python Check Vowel or Not
- Python Check Leap Year or Not
- Check Reverse equal Original
- Check Positive Negative Zero
- Python Check Armstrong or Not
- Python Check Palindrome or Not
- Python Check Perfect Number
- Python Find Reverse of Number
- Python Count Digits in Number
- Python Add Digits of Number
- Sum of First and Last Digits
- Python Product of Mid Digits
- Sum of Squares of Digits
- Interchange Digits of Number
- Python Sum of n Numbers
- Python Print ASCII Values
- Python Swap Two Numbers
- Python Swap Two Variables
- Python Fahrenheit to Celsius
- Python Celsius to Fahrenheit
- Python Display Calendar
- Python Days into Years, Weeks
- Find Largest of Two Number
- Find Largest of Three Number
- Python Print Fibonacci Series
- Generate Armstrong Numbers
- Python Make Simple Calculator
- Python Add Binary Numbers
- Binary Number Multiplication
- Python Mathematical Programs
- Find Sum of Natural Numbers
- Find Average of n Numbers
- Python Print Multiplication Table
- Print Table using Recursion
- Python Find Average Percentage
- Python Find Grade of Student
- Find Square Root of Number
- Python Print Prime Numbers
- Find Numbers Divisible by
- Python Find Factors of Number
- Python Find Factorial of a Number
- Python Find HCF & LCM
- Python Kilometres to Miles
- Python Find Area of Square
- Python Find Area of Rectangle
- Python Find Area of Triangle
- Python Find Area of Circle
- Python Find Perimeter of Square
- Find Perimeter of Rectangle
- Python Find Perimeter of Triangle
- Find Circumference of Circle
- Python Simple Interest
- Python Solve Quadratic Equation
- Python Different Set of Operations
- Python Display Powers of 2
- Python Find nCr & nPr
- Python Pattern Programs
- Python Print Pattern Programs
- Python Print Diamond Pattern
- Python Print Floyd's Triangle
- Python Print Pascal's Triangle
- Python List Programs
- Python Count Even/Odd in List
- Python Positive/Negative in List
- Python Even Numbers in List
- Python Odd Numbers in List
- Python Sum of Elements in List
- Sum of Odd/Even Numbers
- Python Element at Even Position
- Python Element at Odd Position
- Python Search Element in List
- Python Largest Number in List
- Python Smallest Number in List
- Python Second Largest in List
- Python Second Smallest in List
- Python Insert Element in List
- Python Delete Element from List
- Python Multiply Numbers in List
- Swap Two Elements in List
- Python 1D Array Program
- Python Linear Search
- Python Binary Search
- Python Insertion Sort
- Python Bubble Sort
- Python Selection Sort
- Remove Duplicates from List
- Python Reverse a List
- Python Merge Two List
- Python Copy a List
- Python Conversion Programs
- Python Decimal to Binary
- Python Decimal to Octal
- Python Decimal to Hexadecimal
- Python Binary to Decimal
- Python Binary to Octal
- Python Binary to Hexadecimal
- Python Octal to Decimal
- Python Octal to Binary
- Python Octal to Hexadecimal
- Python Hexadecimal to Decimal
- Python Hexadecimal to Binary
- Python Hexadecimal to Octal
- Python Matrix Programs
- Python Add Two Matrices
- Python Subtract Two Matrices
- Python Transpose Matrix
- Python Multiply Matrices
- Python String Programs
- Python Print String
- Python Find Length of String
- Python Compare Two Strings
- Python Copy String
- Python Concatenate String
- Python Reverse a String
- Python Swap Two Strings
- Python Uppercase to Lowercase
- Python Lowercase to Uppercase
- Python Check Substring in String
- Python Count Character in String
- Count Repeated Characters
- Python Count Word in Sentence
- Python Count Each Vowels
- Python Capitalize Character
- Python Capitalize Word in String
- Python Smallest/Largest Word
- Remove Spaces from String
- Remove Duplicate Character
- Remove Vowels from String
- Remove Punctuation from String
- Python Remove Word in String
- Python Remove Duplicate Words
- WhiteSpace to Hyphens
- Replace Vowels with Character
- Replace Character in String
- Python Sort String in Alphabetical
- Sort Word in Alphabetical Order
- Extract Number from String
- Python Check Anagram Strings
- Python File Programs
- Python Read a File
- Python Write to File
- Python Append Text to File
- Python Copy Files
- Python Merge Two Files
- Python Counts Characters in File
- Python Count Words in File
- Python File Content in Reverse
- Python Lines Contains String
- Python Delete Line from File
- Python Capitalize Word in File
- Python Replace Text in File
- Replace Specific Line in File
- Python Find Size of File
- Python List Files in Directory
- Python Delete Files
- Python Misc Programs
- Python Reverse a Tuple
- Python Merge Two Dictionary
- Python bytes to String
- Python bytearray to String
- Generate Random Numbers
- Python Print Address of Variable
- Python Print Date and Time
- Python Get IP Address
- Python Shutdown/Restart PC
- Python Tutorial
- Python Tutorial
Binary Search Program in Python
In this article, you will learn and get code to implement binary search in a Python program. Here is a list of programs for binary search:
- Binary Search using a List with Ordered Inputs
- Binary Search with Random Inputs of a Given Size
- Binary Search using for Loop
Before going through these programs, if you're not aware of the topic, then refer to the binary search logic and algorithm to get everything required.
Binary search using lists
This program searches a number entered by the user using the binary search technique. The program receives 10 numbers from the user and then a number to search using binary search.
nums = [] print("Enter 10 Numbers (in ascending order):") for i in range(10): nums.insert(i, int(input())) print("Enter a Number to Search:") search = int(input()) first = 0 last = 9 middle = (first+last)/2 middle = int(middle) while first <= last: if nums[middle]<search: first = middle+1 elif nums[middle]==search: print("The Number Found at Position:") print(middle+1) break else: last = middle-1 middle = (first+last)/2 middle = int(middle) if first>last: print("The Number is not Found in the List")
Here is its sample run:
Now supply any 10 numbers, say 10, 20, 30, 40, 50, 60, 70, 80, 90, and 100, and then a number, say 60, to search. Here is the sample run with exactly these inputs:
The range() function returns a sequence of values. Its limit is decided by its argument. For example:
for i in range(10): print(i)
prints the value of i ten times, starting from 0 to 9. Therefore, 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 get printed on the output. Each number is printed on a new line. Therefore, the following code (from the above program):
for i in range(10):
is used to execute the following statements:
nums.insert(i, int(input()))
ten times with a value of i from 0 to 9.
Note: The insert() function is used to insert an element into the list (nums[] here). Therefore, the user is allowed to enter the value ten times. And all the values get stored in nums[] in the following way:
- The first number entered by the user gets stored in nums[i] or nums[0].
- The second number gets stored in nums[1].
- The third number gets stored in nums[2].
- and so on up to
- The tenth number gets stored in nums[9].
Note: In above program, the position is printed with a middle+1 value because indexing starts with 0. Therefore, the 0th index's value is referred as the first number.
Binary Search with Random User Inputs of a Given Sizee
This program is similar to the previous one with two extra features. The first one is that this program allows the user to define the size of the list. The second one is that this program doesn't care about the order in which the user enters the data. We've implemented the code to sort the list before applying the binary search technique to search a number.
nums = [] print(end="How Many Number to Enter ? ") tot = int(input()) print(end="Enter " + str(tot) + " Numbers: ") for i in range(tot): nums.insert(i, int(input())) for i in range(tot-1): for j in range(tot-i-1): if nums[j]>nums[j+1]: temp = nums[j] nums[j] = nums[j+1] nums[j+1] = temp print(end="\nThe List is: ") for i in range(tot): print(end=str(nums[i]) + " ") print(end="\nEnter a Number to Search: ") search = int(input()) first = 0 last = tot-1 middle = int((first+last)/2) while first <= last: if nums[middle]<search: first = middle+1 elif nums[middle]==search: print("\nThe Number Found at Position: " + str(middle+1)) break else: last = middle-1 middle = int((first+last)/2) if first>last: print("\nThe Number is not Found in the List")
Here is a sample run with the following user inputs:
- 6 as the size of numbers
- 10, 60, 20, 50, 40, and 30 as 6 numbers
- 30 as the number to search
Based on exactly these inputs, here is the sample run:
Note: The position of the entered number, say 30, gets calculated based on the sorted list, not on the original (unordered) list. because the binary search technique works on a sorted list.
Binary Search using for Loop
To create the same program as the previous one, but using a "for" loop. Then the main thing to change is:
while first <= last:
with this:
for first in range(last+1):
Here is the complete program for binary search using the "for" loop in Python:
nums = [] chk = 0 print(end="How Many Number to Enter ? ") tot = int(input()) print(end="Enter " + str(tot) + " Numbers: ") for i in range(tot): nums.insert(i, int(input())) for i in range(tot-1): for j in range(tot-i-1): if nums[j]>nums[j+1]: temp = nums[j] nums[j] = nums[j+1] nums[j+1] = temp print(end="\nThe List is: ") for i in range(tot): print(end=str(nums[i]) + " ") print(end="\nEnter a Number to Search: ") search = int(input()) first = 0 last = tot-1 middle = int((first+last)/2) for first in range(last+1): if nums[middle]<search: first = middle+1 elif nums[middle]==search: print("\n" + str(search) + " Found at Position: " + str(middle+1)) chk = 1 break else: last = middle-1 middle = int((first+last)/2) if chk!=1: print("\n" + str(search) + " is Not Found in the List!")
Here is its sample run:
« Previous Program Next Program »