Basic Algorithms
def selectionSort (a):
for i in range (len(a) - 1):
# find the minimum
min = a[i]
minIdx = i
for j in range (i + 1, len(a)):
if (a[j] < min):
min = a[j]
minIdx = j
# Swap the minimum element with the element at the ith place
a[minIdx] = a[i]
a[i] = min
def sequentialSearch (a, x):
for i in range (len(a)):
if (a[i] == x):
return i
return -1
def binarySearch (a, x):
lo = 0
hi = len(a) - 1
while (lo <= hi):
mid = (lo + hi) // 2
if (x > a[mid]):
lo = mid + 1
elif (x < a[mid]):
hi = mid - 1
else:
return mid
return -1
def merge (a, b):
c = []
idxA = 0
idxB = 0
while ((idxA < len(a)) and (idxB < len(b))):
if (a[idxA] < b[idxB]):
c.append (a[idxA])
idxA = idxA + 1
else:
c.append (b[idxB])
idxB = idxB + 1
# if a is not empty write it out
while (idxA < len(a)):
c.append (a[idxA])
idxA = idxA + 1
# if b is not empty write it out
while (idxB < len(b)):
c.append (b[idxB])
idxB = idxB + 1
return c
def main():
print ("Test selection sort")
a = [9, 1, 8, 2, 7, 3, 6, 4, 5]
print (a)
selectionSort (a)
print (a)
print ()
print ("Test sequential search")
x = 3
print (str(x) + " " + str(sequentialSearch (a, x)))
x = 25
print (str(x) + " " + str(sequentialSearch (a, x)))
print ()
print ("Test binary search")
x = 3
print (str(x) + " " + str(binarySearch (a, x)))
x = 25
print (str(x) + " " + str(binarySearch (a, x)))
print ()
print ("Test merge")
a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8]
c = merge (a, b)
print (a)
print (b)
print (c)
print ()
main()