Sort and Search - BenWare-FED/Python GitHub Wiki

Bubble sort:

does two things. It does this by placing one of the values in a placeholder

  1. Comparison of 2 adjacent values

  2. Swap two adjacent values

code for making an ascending sort

for i in range(0, len(list) -1):

if (list[j] > list[j+1]):
    
    temp = list[j]
    
    list[j] = list[j+1]
    
    list[j+1] = temp

linear search

takes a long time

for i in range (0, len(list)):

if (list(i) == target):
    
    print("Target found")

Binary Search

List must be presorted. This sort works by continuedly finding the middle element and determining if the target value is higher or lower. You find the middle element by adding the index number to the index number of the end and dividing by two. The resulting number is the index number of the element that will be checked next.

start = 0

end = len(list)-1

While(start <= end):

mid = (start + end) // 2

if (list[mid] == target):
    
    print("Target found.")

elif(list[mid] < target):

    start = mid + 1

else:

    end = mid -1