0% found this document useful (0 votes)
48 views4 pages

Binary Search: Step by Step Example

The document discusses binary search, an algorithm that finds the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half and determining which half may contain the target value. The algorithm executes in logarithmic time. Step-by-step examples are provided in Python pseudocode to demonstrate how binary search is implemented and works on sample inputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views4 pages

Binary Search: Step by Step Example

The document discusses binary search, an algorithm that finds the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half and determining which half may contain the target value. The algorithm executes in logarithmic time. Step-by-step examples are provided in Python pseudocode to demonstrate how binary search is implemented and works on sample inputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 4

Binary Search

In computer science, a binary search or half-interval search algorithm finds the position of a target value
within a sorted array. The binary search algorithm can be classified as a dichotomies divide-and-conquer
search algorithm and executes in logarithmic time.
Step by step example:
Program:

a=[]
x=int(input("Enter Upper Limit : "))
for i in range(0,x):
e=int(input("Enter the Elements : "))
a.append(e)
n=int(input("Enter the element to be Searched : "))

#a=[1,2,3,4,5,8,10,6]
#n=int(input('Enter the element to be Searched : '))
l=0
u=len(a)-1
while(l<=u):
mid=(l+u)//2
if(n==a[mid]):
print('The element is at position',mid)
break
elif(n>a[mid]):
l=mid+1
else:
u=mid-1
else:
print('The element is Not Found')

Output:
Enter the element to be Searched: 8
The element is at position 5

Enter the element to be Searched: 15


The element is Not Found
Python Code:

def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found

print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))

Sample Output:
False
True
Flowchart:

You might also like