python笔记:简单的查找与排序算法

来源:互联网 发布:腾讯云计算数据中心 编辑:程序博客网 时间:2024/03/29 15:33

最近在看麻省理工《计算机科学与编程导论》的那个公开课,第九课讲了一些简单而又基础的一些搜索与排序的算法,用python实现。之前学的是c,因为前段时间看不下去了,所以开了个小差,来学python了,也深深感觉到python的魅力。下面贴代码:

def bsearch(s, e, first, last, calls):print first, " ", last, " ", calls if (last - first) <= 1: #必须考虑lase==first的情况return first == e or last == emid = (first + last) / 2if(mid == e):return Trueelse:if mid > e:return bsearch(s, e, first, mid-1, calls+1)else:return bsearch(s, e, mid+1, last, calls+1)def search(s, e):print bsearch(s, e, 0, len(s)-1, 1)def selSort(L):print Lfor i in range(len(L) - 1):minIndex = iminVal = L[i]j = i + 1while j < len(L):if minVal > L[j]:minIndex = jminVal = L[j]j = j + 1L[i], L[minIndex] = L[minIndex], L[i]  #a,b = b, a    交换两个数print Ldef testSelSort():test1 = [1,6,3,4,5,2]raw_input("第一组数:")selSort(test1)test2 = [6,1,2,3,4,5]raw_input("第二组数:")selSort(test2)test3 = [6,5,4,3,2,1]raw_input("第三组数:")selSort(test3)test4 = [1,2,3,4,5,6]raw_input("第四组数:")selSort(test4)def bubbleSort1(L):print Lfor i in range(len(L)):for j in range(len(L) - 1 - i):if L[j] > L[j+1]:L[j], L[j+1] = L[j+1], L[j]print Ldef bubbleSort2(L):print Lswaped = Truewhile swaped:swaped = Falsefor i in range(len(L) - 1):if L[i] > L[i+1]:L[i], L[i+1] = L[i+1], L[i]swaped = Trueprint Ldef testBubbleSort1():        test1 = [1,6,3,4,5,2]        raw_input('运行冒泡排序测试1')        bubbleSort1(test1)        test2 = [6,1,2,3,4,5]        raw_input('运行冒泡排序测试2')        bubbleSort1(test2)        test3 = [6,5,4,3,2,1]        raw_input('运行冒泡排序测试3')        bubbleSort1(test3)        test4 = [1,2,3,4,5,6]        raw_input('运行冒泡排序测试4')        bubbleSort1(test4)def testBubbleSort2():    test1 = [1,6,3,4,5,2]    raw_input('运行冒泡排序测试1')    bubbleSort2(test1)    test2 = [6,1,2,3,4,5]    raw_input('运行冒泡排序测试2')    bubbleSort2(test2)    test3 = [6,5,4,3,2,1]    raw_input('运行冒泡排序测试3')    bubbleSort2(test3)    test4 = [1,2,3,4,5,6]    raw_input('运行冒泡排序测试4')    bubbleSort2(test4)


原创粉丝点击