Answer to Question #322482 in Python for Juhan

Question #322482

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

1
Expert's answer
2022-04-02T09:59:47-0400

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()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS