added sorting exercise
This commit is contained in:
27
loops/sort/solution/sort.py
Normal file
27
loops/sort/solution/sort.py
Normal file
@ -0,0 +1,27 @@
|
||||
from copy import deepcopy
|
||||
from typing import Iterator, Optional
|
||||
|
||||
|
||||
def selection_sort[T](xs: Iterator[T]) -> Iterator[T]:
|
||||
length = len(xs)
|
||||
xss = deepcopy(xs)
|
||||
for i in range(length):
|
||||
min_i = i
|
||||
for j in range(i + 1, length):
|
||||
if xss[j] < xss[min_i]:
|
||||
min_i = j
|
||||
xss[i], xss[min_i] = xss[min_i], xss[i]
|
||||
return xss
|
||||
|
||||
def binary_search[T](xs: list[T], value: T) -> Optional[int]:
|
||||
left = 0
|
||||
right = len(xs) - 1
|
||||
while left <= right:
|
||||
middle = (left + right) // 2
|
||||
if xs[middle] < value:
|
||||
left = middle + 1
|
||||
elif xs[middle] > value:
|
||||
right = middle - 1
|
||||
else:
|
||||
return middle
|
||||
return None
|
Reference in New Issue
Block a user