[超水笔记之三]北大慕课:数据结构与算法Python版

顺序查找Sequential Search

顺序查找:

无序表查找

def sequentialSearch(alist,item):
    pos = 0
    found = False
    
    while pos<len(alist) and not found:
        if alist[pos] == item:
            found =True
        else:
            pos += 1
    return found

有序表查找

def orderedSequentialSearch(alist,item):
    pos = 0
    found = False
    stop = False
    while pos<len(alist) and not found and not stop:
        if alist[pos] == item:
            found = True
        else:
            if alist[pos] > item:
                stop = True
            else:
                pos += 1
    return found

二分查找:分而治之

  • 二分查找代码:
def binarySearch(alist,item):
    first = 0
    last = len(alist)-1
    found = False

    while first<=last and not found:
        midpoint = (first+last)/2
        if alist[midpoint]==item:
            found = True
        else:
            if item<alist[midpoint]:
                last = midpoint-1
            else:
                first = midpoint+1
    return found
  • 二分查找代码—递归
def binarySearch(alist,item):
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist)/2
        if alist[midpoint] == item:
            return True
        else:
            if item<alist[midpoint]:
                return binarySearch(alist[:midSearch],item)
            else:
                return binarySearch(alist[midpoint+1:],item)

注:递归调用了列表切片,其复杂度为O(K),其中K为切片长度。这使算法时间复杂度稍有增加

总结

二分查找在时间复杂度上优于顺序查找。若一次排序后可进行多次查找,那么排序的开销可以摊薄;若数据经常变动,查找次数相对较少,则可能还是直接使用无序表更优

排序

冒泡排序Bubble Sort

冒泡排序算法的思路在于对无序表进行多趟比较交换。每趟包括了多次两两相邻比较,
并将逆序的数据项交换位置,最终能将本趟的最大项就位。经过n-1趟比较,实现整表排序。
每趟的过程类似“气泡”在水上不断上浮到水面的过程。

冒泡排序第一趟

  • 代码:
def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp  # <=> alist[i],alist[i+1] = alist[i+1],alist[i]

常见算法可视化

  • 冒泡排序算法分析:
  1. 冒泡排序时间效率较差,复杂度 O ( n 2 ) O(n^{2}) O(n2)
  2. 优势:无需任何额外的存储空间开销
  • 代码:性能改进
def shortBubbleSort(alist):
    exchange = True
    passnum = len(alist)-1
    while passnum > 0 and exchange:
        exchange = False
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                exchange = True
                alist[i],alist[i+1] = alist[i+1],alist[i]

        passnum = passnum-1
  • 选择排序Selection Sort
    选择排序
  • 代码:
def selectionSort(alist):
    for fillslot in range(len(alist)-1,0,-1):
        positionOFMAX = 0
        for location in range(1,fillslot+1):
            if alist[location]>alist[positionOFMAX]:
                positionOFMAX = location

        temp = alist[fillslot]
        alist[fillslot] = alist[positionOFMAX]
        alist[positionOFMAX] = temp

插入排序Insertion Sort

插入排序

  • 代码:
def insertionSort(alist):
    for index in range(1,len(alist)):

        currentvalue = alist[index]
        position = index

        while position>0 and alist[position-1]>currentvalue:
            alist[positon]=alist[position-1]
            position -= 1

        alist[position] = currentvalue

谢尔排序Shell Sort

一句话概括:对子列表进行排序

  • 代码:
def shellSort(alist):
    sublistcount = len(alist)//2  # 返回整数值
    while sublistcount>0:
        for startposition in range(sublistcount):
            gapInsertionSort(alist,startPosition,sublistcount)
        print("after increments of size",sublistcount,
              "the list is ",alist)
        sublistcount = sublistcount//2

def gapInsertionSort(alist,start,gap):
    for i in range(start+gap,len(alist),gap):
        currentvalue = alist[i]
        position = i
        while position>=gap and alist[position-gap]>currentvalue:
            alist[positon] = alist[position-gap]
            position -= gap

        alist[position] = currentvalue

归并排序Merge Sort

  • 代码:
def mergeSort(alist):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i = j = k = 0
        while i< len(lefthalf) and j<len(righthalf):
            if lefthalf[i]<righthalf[j]:
                alist[k]=lefthalf[i]
                i+=1

            else:
                alist[k] = righthalf[j]
                j+=1
            k+=1

        while i <len(lefthalf):
            alist[k] = lefthalf[i]
            i+=1
            k+=1

        while j<len(righthalf):
            alist[k]=righthalf[j]
            j+=1
            k+=1
  • more pythonic:
def merge_sort(lst):
    if len(lst)<=1:
        return lst
    
    middle = len(lst)//2
    left = merge_sort(lst[:middle])
    right = merge_sort(lst[middle:])
    
    merged = []
    while left and right:
        if left[0] <= right[0]:
            merged.append(left.pop(0))
        else:
            merged.append(right.pop(0))
    merged.extend(right if right else left)
    return merged

快速排序Quick Sort

  • 思路: 依据一个中值数据项将数据表分为两半,每部分分别进行快速排序(递归)

  • 代码:

def quickSort(alit):
    quickSortHelper(alist,0,len(alist)-1)

def quickSortHelper(alist,first,last):
    if first<last:
        splitpoint = partition(alist,first,last)
        quickSortHelper(alist,first,splitpoint-1)
        quickSortHelper(alist,splitpoint+1,last)

def partition(alist,first,last):
    pivotvalue = alist[first]
    leftmark = first+1
    rightmark = last

    done = False
    while not done:
        while leftmark<=rightmark and \
            alist[leftmark]<=pivotvalue:
            leftmark +=1
        while alist[rightmark]>=pivotvalue and \
            rightmark>=leftmark:
            rightmark -=1
        if rightmark<leftmark:
            done=True
        else:
            temp = alist[leftmark]
            alist[leftmark]= alist[rightmark]
            alist[rightmark] = temp

    temp = alist[first]
    alist[first] = alist[rightmark]
    alist[rightmark] = temp

    return rightmark

未完待续。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值