Untitled

mail@pastecode.io avatar
unknown
python
a month ago
1.1 kB
5
Indexable
Never
def smallest(v):
    small = v[0]
    for i in range(1, len(v)):
        if v[i] < small:
            small = v[i]
    return small

def linearSearch(v, target):
    for i in range(len(v)):
        if v[i] == target:
            return i
    return -1

def binarySearch(v, target):
    if len(v) == 0:
        return False
    
    mid = len(v) // 2
    if v[mid] == target:
        return True
    elif target > v[mid]:
        return binarySearch(v[mid+1:], target)
    else:
        return binarySearch(v[:mid-1], target)
    
def selectionSort(v):
    for i in range(len(v)):
        small = i
        for j in range(i + 1, len(v)):
            if v[j] < v[small]:
                small = j
                
        if i != small:
        	# scambiamo v[i] con v[small]
            t = v[i]
            v[i] = v[small]
            v[small] = t

print(linearSearch([7, 2, 1, 6, 4], 6))
print(linearSearch([7, 2, 1, 6, 4], 3))
print(binarySearch([1, 3, 7, 9, 13, 14], 3))
print(binarySearch([1, 3, 7, 9, 13, 14], 8))

v = [5, 2, 3, 9, 8, 12]
selectionSort(v)
Leave a Comment