Categories:Viewed: 7 - Published at: a few seconds ago

Write a python program to Implement Binary Search without Recursion and print the key element if found

def binary_search(alist, key):
    """Search key in alist[start... end - 1]."""
    start = 0
    end = len(alist)
    while start < end:
        mid = (start + end)//2
        if alist[mid] > key:
            end = mid
        elif alist[mid] < key:
            start = mid + 1
        else:
            return mid
    return -1


alist = [2, 3, 5, 6, 4, 5]

key = 6

index = binary_search(alist, key)
if index < 0:
    print(f'{key} was not found.')
else:
    print(f'{key} was found at index {index}.')

Write a python program to Implement Binary Search with Recursion and print the key element if found

def binary_search_rec(alist, start, end, key):
    """Search key in alist[start... end - 1]."""
    if not start < end:
        return -1

    mid = (start + end)//2
    if alist[mid] < key:
        return binary_search_rec(alist, mid + 1, end, key)
    elif alist[mid] > key:
        return binary_search_rec(alist, start, mid, key)
    else:
        return mid


alist = [2, 3, 5, 6, 4, 5]

key = 6

index = binary_search_rec(alist, 0, len(alist), key)
if index < 0:
    print(f'{key} was not found.')
else:
    print(f'{key} was found at index {index}.')

Write a python program to Implement Bubble sort and print the sorted list for the below list

def bubble_sort(alist):
    for i in range(len(alist) - 1, 0, -1):
        no_swap = True
        for j in range(0, i):
            if alist[j + 1] < alist[j]:
                alist[j], alist[j + 1] = alist[j + 1], alist[j]
                no_swap = False
        if no_swap:
            return


alist = [2, 3, 5, 6, 4, 5]
bubble_sort(alist)
print('Sorted list: ', end='')
print(alist)

Write a python program to Implement Selection sort and print the sorted list for the below list

def selection_sort(alist):
    for i in range(0, len(alist) - 1):
        smallest = i
        for j in range(i + 1, len(alist)):
            if alist[j] < alist[smallest]:
                smallest = j
        alist[i], alist[smallest] = alist[smallest], alist[i]


alist = [2, 3, 5, 6, 4, 5]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)

Write a python program to Implement Insertion sort and print the sorted list for the below list

def insertion_sort(alist):
    for i in range(1, len(alist)):
        temp = alist[i]
        j = i - 1
        while (j >= 0 and temp < alist[j]):
            alist[j + 1] = alist[j]
            j = j - 1
        alist[j + 1] = temp


alist = [2, 3, 5, 6, 4, 5]
insertion_sort(alist)
print('Sorted list: ', end='')
print(alist)