0% found this document useful (0 votes)
6 views1 page

Binary Search

The document creates an unsorted array, sorts it using bubble sort, then performs a binary search to find a specified element and outputs the number of iterations.

Uploaded by

symbattgysbaj7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Binary Search

The document creates an unsorted array, sorts it using bubble sort, then performs a binary search to find a specified element and outputs the number of iterations.

Uploaded by

symbattgysbaj7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

Create an unordered array from 1 to n elements.

Sort array in ascending order and


find where the specified element is with binary search. Find the number of
iteration in finding an element. (но здесь есть ошибка при выводе ошибочного
элемента, а в целом код работает)

array = []
for i in range(1, 10):
elem = int(input('input elements:'))
array.append(elem)
print(array)

def bubble(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr

s_array = bubble(array)
print(s_array)

lost_elem = int(input())
low = 0
high = len(array) - 1
it = 0
while low <= high:
mid = (low + high) // 2
if array[mid] == lost_elem:
print(lost_elem, 'found at index', mid)
it += 1
break
elif array[mid] > lost_elem:
high = mid - 1
it += 1
elif array[mid] < lost_elem:
low = mid - 1
it += 1
else:
print(lost_elem, 'not found')
print(it, 'number of iterations')

You might also like