Lecture 9: Binary search, bubble and selection sorts

# Lecture 9 fall 2008

def bsearch(s, e, first, last, calls):
    print (first, last, calls)
    if (last - first) < 2:
        return s[first] == e or s[last] == e
    mid = first + (last - first)//2
    if s[mid] == e: return True
    if s[mid] > e: return bsearch(s, e, first, mid - 1, calls + 1)
    return bsearch(s, e, mid + 1, last, calls + 1)

def search(s,e):
    print (bsearch(s, e, 0, len(s) - 1, 1))

# Selection Sort
def selSort(L):
    for i in range(len(L) - 1):
        minIndx = i
        minVal = L[i]
        j = i + 1
        while j < len(L):
            if minVal > L[j]:
                minIndx = j
                minVal = L[j]
            j = j + 1
        temp = L[i]
        L[i] = L[minIndx]
        L[minIndx] = temp
        print (L)

def testSelSort():
    test1 = [1,6,3,4,5,2]
    input ('run selective test 1')
    selSort(test1)
    test2 = [6,1,2,3,4,5]
    input ('run selective test 2')
    selSort(test2)
    test3 = [6,5,4,3,2,1]
    input ('run selective test 3')
    selSort(test3)
    test4 = [1,2,3,4,5,6]
    input ('run selective test 4')
    selSort(test4)

# Bubble Sort
def bubbleSort(L):
    for j in range(len(L)):
        for i in range(len(L) - 1):
            if L[i] > L[i+1]:
                temp = L[i]
                L[i] = L[i+1]
                L[i+1] = temp
        print (L)

def bubbleSort1(L):
    swapped = True
    while swapped:
        swapped = False
        for i in range(len(L) - 1):
            if L[i] > L[i+1]:
                temp = L[i]
                L[i] = L[i+1]
                L[i+1] = temp
                swapped = True
        print (L)
        
def testBubbleSort():
    test1 = [1,6,3,4,5,2]
    input ('run selective test 1')
    bubbleSort(test1)
    test2 = [6,1,2,3,4,5]
    input ('run selective test 2')
    bubbleSort(test2)
    test3 = [6,5,4,3,2,1]
    input ('run selective test 3')
    bubbleSort(test3)
    test4 = [1,2,3,4,5,6]
    input ('run selective test 4')
    bubbleSort(test4)

def test():
    for i in range(5):
        print (i)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值