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

Binary Search: Source Code

This document describes the binary search algorithm for searching an element in a sorted list. It takes a sorted list and element as input, calculates the mid-point of the list each iteration, compares the element to the mid-point value, and updates the search space to the left or right of the mid-point accordingly until the element is found or the entire list has been searched through, at which point it returns the index or -1. It provides an implementation of binary search in Python code along with sample input/output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Binary Search: Source Code

This document describes the binary search algorithm for searching an element in a sorted list. It takes a sorted list and element as input, calculates the mid-point of the list each iteration, compares the element to the mid-point value, and updates the search space to the left or right of the mid-point accordingly until the element is found or the entire list has been searched through, at which point it returns the index or -1. It provides an implementation of binary search in Python code along with sample input/output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

BINARY SEARCH

SOURCE CODE:
def binarysearch(List, elem):

beg = 0

last=len(List)-1

while(beg<=last):

mid=(beg+last)/2

if(elem==List[mid]):

return mid

elif(elem>List[mid]):

beg=mid+1

else:

last=mid-1

return -1

n=input('enter lenghth of list:')

List=[0]*n

for j in range(n):

List[j]=input('Enter element:')

elem=input('Enter element to be searched for:')

index=binarysearch(List, elem)

if index:
print'Element found at index', index, 'position =', index + 1

else:

print 'Element not found'

OUTPUT:

You might also like