Using function:
a. sort a list using bubble sort algorithm (ascending and descending order). you have
to take choice from the user. also the list should be user defined
b. search an item using binary search algorithm
a.
def bubblesort(L, ascending=True):
n = len(L)
for i in range(n-1):
for j in range(n-1,i,-1):
if ascending:
if L[j] < L[j-1]:
L[j], L[j-1] = L[j-1], L[j]
else:
if L[j] > L[j-1]:
L[j], L[j-1] = L[j-1], L[j]
def main():
line = input('Enter a list: ')
L = [int(s) for s in line.split()]
line = input('Ascendding or Descending order? - ')
if line[0] == 'a' or line[0] == 'A':
ascending = True
else:
ascending = False
bubblesort(L, ascending)
print('Soreted list:', L)
if __name__ == '__main__':
main()
b.
def binsearch(L, x):
l = 0
h = len(L) - 1
while h > l:
m = (h + l) // 2
if L[m] == x:
return True
if L[m] < x:
l = m+1
else:
h = m-1
return False
def main():
line = input("Entear a list: ")
L = [int(s) for s in line.split()]
L.sort()
x = int(input('Enter a number: '))
if binsearch(L, x):
print('The number is present in the list')
else:
print('The number is not in the list')
if __name__ == '__main__':
main()
Comments
Leave a comment