《数据结构(Python语言描述)》代码整理(更新中……)

文章目录

  • 第3章 搜索、排序和复杂度分析
    • 搜索算法
    • 基本排序算法
  • 第7章 栈

第3章 搜索、排序和复杂度分析

搜索算法

搜索最小值

def indexOfMin(lyst):
    minIndex = 0
    currentIndex = 1
    while currentIndex < len(lyst):
        if lyst[currentIndex] < lyst[minIndex]:
            minIndex = currentIndex
        currentIndex += 1
    return minIndex

顺序搜索列表

def sequentialSearch(target, lyst):
    position = 0
    while position < len(lyst):
        if target == lyst(position):
            return position
        position += 1
    return -1

有序列表的二叉搜索

def binarySearch(target, sortedLyst):
    left = 0
    right = len(sortedLyst) - 1
    while left <= right:
        mid = (left + right) // 2
        if target == sortedLyst(mid):
            return mid
        elif target < sortedLyst(mid):
            right = mid - 1
        else:
            left = mid + 1
    return -1

搜索二叉搜索树

class treeNode():
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class Solution():
    def find(self, node, target):
        def recurse(node):
            if node is None:
                return None
            elif target == node.val:
                return node.val
            elif target < node.val:
                return recurse(node.left)
            else:
                return recurse(node.right)
        return recurse(node)

基本排序算法

选择排序(selection sort):搜索整个列表,找到最小项的位置,如果该位置不是列表的第1个位置,就交换这两个位置的项,然后回到列表的第2个位置重复这个步骤。算法复杂度为 O ( n 2 ) O(n^2) O(n2)

class Solution():
    def selectionSort(self, lyst):
        i = 0
        while i < len(lyst) - 1:
            minIndex = i
            j = i + 1
            while j < len(lyst):
                if lyst[j] < lyst[minIndex]:
                    minIndex = j
                j += 1
            if minIndex != i:
                self.swap(lyst, minIndex, i)
            i += 1
        return lyst

    def swap(self, lyst, i, j):
        temp = lyst[i]
        lyst[i] = lyst[j]
        lyst[j] = temp

冒泡排序(bubble sort):从列表的开头处开始,依次比较相邻两项的数据,如果前一个数据大于后一个数据则交换两项,否则不变。这样将把最大的项以冒泡的方式排到列表的末尾,然后从列表头到倒数第二个列表项重复这一过程,直到从列表的最后一项开始执行。算法复杂度为 O ( n 2 ) O(n^2) O(n2)

def bubbleSort(lyst):
    n = len(lyst)
    while n > 1:
        swapped = False
        i = 1
        while i < n:
            if lyst[i] < lyst[i - 1]:
                swap(lyst, i, i - 1)
                swapped = True
            i += 1
        if not swappend:
            return lyst
        n -= 1
    return lyst

插入排序(insertion sort)

def insertionSort(lyst):
    i = 1
    while i < len(lyst):
        itemToInsert = lyst[i]
        j = i - 1
        while j >= 0:
            if itemToInsert < lyst[j]:
                lyst[j + 1] = lyst[j]
                j -= 1
            else:
                break
        lyst[j + 1] = itemToInsert
        i += 1
    return lyst

第7章 栈

匹配括号:编译器需要判断表达式中的括号是否正确匹配,例如每个开始的‘(’的后面都应该跟着一个结束的’)’。可以利用栈来实现这一功能。

def bracketsBalance(exp):
    ''' exp是一个表达式,例如:'()[]{}','{[()]}' '''
    stk = [] # 通过列表来实现栈
    for ch in exp:
        if ch in ['(', '[', '{']:
            stk.append(ch)
        elif ch in [')', ']', '}']:
            if stk == []:
                return False
            chFromStack = stk.pop()
            if ch == ')' and chFromStack != '(' or \
               ch == ']' and chFromStack != '[' or \
               ch == '}' and chFromStack != '{':
               return False
    return stk == []

你可能感兴趣的:(学习笔记)