[Python] 數據結構與算法筆記(排序與查找)

3 排序與查找

可視化資料:https://visualgo.net/zh/sorting

3.1 順序查找算法及分析

無序表查找:

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

testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]
print(sequentialSearch(testlist,3))

在這裏插入圖片描述

順序查找:

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

testlist = [0, 1, 2, 8, 17, 19, 42]
print(orderedSequentialSearch(testlist,3))

在這裏插入圖片描述

3.2 二分查找算法及分析

對於有序表,從列表中間開始對比。
分而治之

def binarySearch(alist, item):
    first = 0
    last = len(alist) - 1
    found = False

    while first <= last and not found:
        mid = (first + last) // 2
        if alist[mid] == item:
            found = True
        else:
            if alist[mid] > item:
                last = mid - 1
            else:
                first = mid + 1
    return found

testlist = [0, 1, 2, 8, 17, 19, 42]
print(binarySearch(testlist,3))

在這裏插入圖片描述

3.2 冒泡和選擇排序算法及分析

3.2.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]     #PYTHON支持直接交換

testlist = [0, 55, 2, 31, 17, 19, 42]
bubbleSort(testlist)
print(testlist)

在這裏插入圖片描述
在這裏插入圖片描述

3.2.2 選擇排序

def selectSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        positioOfMax = 0
        for i in range(1,passnum+1):
            if alist[i] > alist[positioOfMax]:
                positioOfMax = i

        temp = alist[passnum]
        alist[passnum] = alist[positioOfMax]
        alist[positioOfMax] = temp

testlist = [0, 55, 2, 31, 17, 19, 42]
selectSort(testlist)
print(testlist)

3.3 插入排序與謝爾排序算法及分析

3.3.1 插入排序

def insertSort(alist):
    for index in range(1, len(alist)):
        currentvalue = alist[index]
        position = index

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

        alist[position] = currentvalue

testlist = [0, 55, 2, 31, 17, 19, 42]
insertSort(testlist)
print(testlist)

3.3.2 謝爾排序算法及分析

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

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[position] = alist[position-gap]
            position = position - gap
            
        alist[position] = currentvalue

在這裏插入圖片描述

3.4 歸併排序算法及分析

在這裏插入圖片描述

def mergeSort(alist):
    if len(alist) <= 1:      # 遞歸結束條件
        return alist

        # 分解問題,並遞歸調用
        mid = len(alist) // 2
        lefthalf = mergeSort(alist[:mid])
        righthalf = mergeSort(alist[mid:])

        # 合併左右半部,完成排序
        merged = []
        while lefthalf and righthalf:
            if lefthalf[0] <= righthalf[0]:
                merged.append(lefthalf.pop(0))
            else:
                merged.append(righthalf.pop(0))

        merged.extend(righthalf if righthalf else lefthalf)
        return merged


在這裏插入圖片描述
在這裏插入圖片描述

3.4 快速排序算法及分析

在這裏插入圖片描述

def quickSort(alist):
    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 leftmark <= rightmark and alist[rightmark] >= pivotvalue:
            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

alist = [54, 25, 31, 20, 77, 44, 55, 17]
quickSort(alist)
print(alist)

在這裏插入圖片描述
在這裏插入圖片描述

3.5 散列/哈希表

3.5.1 定義

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

3.5.2 散列函數

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

import hashlib

print(hashlib.md5("hello world!".encode("utf-8")).hexdigest())

print(hashlib.sha1("hello world!".encode("utf-8")).hexdigest())

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

3.5.3 散列函數設計

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

def hash(astring, tablesize):
    sum = 0
    for pos in range(len(astring)):
        sum += ord(astring[pos])
        
    return sum%tablesize

在這裏插入圖片描述
在這裏插入圖片描述

3.5.4 衝突解決

1.開放定址
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
2.數據鏈條
在這裏插入圖片描述
在這裏插入圖片描述

3.6 抽象數據類型及Python實現

在這裏插入圖片描述
在這裏插入圖片描述

幾個小算法

輸出列表元素,以空格/逗號爲分隔符

l=[1,2,3,4]
for i in l:
    print(i,end=' ')	#以空格爲分隔符

輸出:1 2 3 4 (注意,此時4後面還有一個空格)

l = [1,2,3,4]  
print(",".join(str(i) for i in l))

輸出:1,2,3,4(注意,此時4後面沒有逗號)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章