15-112 Fundamentals of Programming

Notes - Lecture 3.2


Efficiency

Sections 1, 2, 3, 4, 5.1, 5.2 and 5.4 from here.

Linear search and binary search

def linearSearch(L, target):
    for index in range(len(L)):
        if(L[index] == target):
            return True
    return False


def binarySearch(L, target):      
    start = 0
    end = len(L) - 1           
    while(start <= end):
        middle = (start + end)//2
        if(L[middle] == target): 
            return True
        elif(L[middle] > target): 
            end = middle-1
        else: 
            start = middle+1
    return False

Selection sort and bubble sort

def swap(L, i, j):
    (L[i], L[j]) = (L[j], L[i])


def selectionSort(L):
    N = len(L)
    for startIndex in range(N):
        minIndex = startIndex
        for i in range(startIndex+1, N):
            if(L[i] < L[minIndex]):
                minIndex = i
        swap(L, startIndex, minIndex)


def bubbleSort(L):
    N = len(L)
    end = N
    swapped = True
    while(swapped):
        swapped = False
        for i in range(1, end):
            if(L[i-1] > L[i]):
                swap(L, i-1, i)
                swapped = True
        end -= 1



Valid CSS! Valid XHTML 1.0 Strict