-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithms.py
More file actions
25 lines (24 loc) · 730 Bytes
/
algorithms.py
File metadata and controls
25 lines (24 loc) · 730 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# ---------------- Algorithms ----------------
def selection_sort(arr):
"""Selection sort - returns a new sorted list. O(n^2)"""
a = list(arr)
n = len(a)
for i in range(n):
min_i = i
for j in range(i + 1, n):
if a[j] < a[min_i]:
min_i = j
a[i], a[min_i] = a[min_i], a[i]
return a
def binary_search(sorted_list, target):
"""Binary search on a sorted list. Returns index or -1. O(log n)"""
lo, hi = 0, len(sorted_list) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sorted_list[mid] == target:
return mid
elif sorted_list[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1