Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jigi-33/3c4716e10b2bdd12ce4c5b810d1ddcba to your computer and use it in GitHub Desktop.
Save jigi-33/3c4716e10b2bdd12ce4c5b810d1ddcba to your computer and use it in GitHub Desktop.
Классические алгоритмы из понятной классической книги
"""
Классические алгоритмы из книги
Problem Solving with Algorithms and Data Structures Release 3 (by B.Miller, D.Ranum)
"""
# Bubble softing algorithm (сортировка пузырьком)
def bubble_sort(a_list):
for pass_num in range(len(a_list) - 1, 0, -1):
for i in range(pass_num):
if a_list[i] > a_list[i + 1]:
temp = a_list[i]
a_list[i] = a_list[i + 1]
a_list[i + 1] = temp
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubble_sort(a_list)
print(a_list)
# Секвентивный поиск
def sequential_search(a_list, item):
pos = 0
found = False
while pos < len(a_list) and not found:
if a_list[pos] == item:
found = True
else:
pos = pos+1
return found
test_list = [1, 2, 32, 8, 17, 19, 42, 13, 0]
print(sequential_search(test_list, 3))
print(sequential_search(test_list, 13))
# Бинарный поиск
def binary_search(a_list, item):
first = 0
last = len(a_list) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if a_list[midpoint] == item:
found = True
elif:
if item < a_list[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found
test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binary_search(test_list, 3))
print(binary_search(test_list, 13))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment