zoukankan      html  css  js  c++  java
  • 算法_python各种排序的代码实现

    python各种排序的代码实现

    冒泡排序

    # 冒泡排序
    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
        return alist
    

    选择排序

    # 选择排序
    def selectSort(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
                if positionOfMax != fillslot:
                    alist[fillslot], alist[positionOfMax] = alist[positionOfMax], alist[fillslot]
        return alist            
        
    alist = [4, 8, 1, 9, 2, 0, 3, 7, 5, 6]
    print(selectSort(alist))
    

    插入排序

    # 插入排序
    def insertSort(alist):
        for index in range(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
            
        return alist
    
    alist = [4, 8, 1, 9, 2, 0, 3, 7, 5, 6]
    print(insertionSort(alist))
    

    希尔排序

    # 希尔排序
    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, "Then list is", alist)
            sublistcount = sublistcount // 2
        return alist
    
    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
    
    alist = [4, 8, 1, 9, 2, 0, 3, 7, 5, 6]
    print(shellSort(alist))
    

    归并排序

    # 归并排序--递归实现
    def mergeSort(alist=[]):
        if len(alist) <= 1:
            return alist
        else:
            mid = len(alist) // 2
            left = []
            right = []
            left = mergeSort(alist[:mid])
            right = mergeSort(alist[mid:])
            return merge(left, right)
            
    def merge(left=[], right=[]):
        # i, j are index for left and right seperately
        i, j = 0, 0
        result = []
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                result.append(left[i])
                i += 1
            else:
                result.append(right[j])
                j += 1
        
        # 将剩余部分依次加入 result
        result = result + left[i:]
        result = result + right[j:]
        return result
    
    alist = [4, 8, 1, 9, 2, 0, 3, 7, 5, 6]
    print(mergeSort(alist))
    

    快速排序

    # 快速排序
    def quicksort(collection):
        length = len(collection)
        if length <= 1:
            return collection
        else:
            # Use the last element as the first pivot
            pivot = collection.pop()
            # Put elements greater than pivot in greater list
            # Put elements lesser than pivot in lesser list
            greater, lesser = [], []
            for element in collection:
                if element > pivot:
                    greater.append(element)
                else:
                    lesser.append(element)
            return quicksort(lesser) + [pivot] + quicksort(greater)
    
    
    if __name__ == '__main__':
        list1 = [7, 3, 23, 6, 9, 9, 10]
        res = quicksort(list1)
        print(res)
    

    堆排序

    本段代码来自github

    def heapify(unsorted, index, heap_size):
        """制作一个大根堆"""
        largest = index
        left_index = 2 * index + 1  # 左子节点的索引位置
        right_index = 2 * index + 2  # 右子节点的索引位置
        if left_index < heap_size and unsorted[left_index] > unsorted[largest]:  # 存在左子节点并且左子节点大于父节点
            largest = left_index  # 最大节点的索引为 左子节点的索引
    
        if right_index < heap_size and unsorted[right_index] > unsorted[largest]:  # 存在右子节点并且右子节点的值大于左子节点的值
            largest = right_index  # 最大节点的索引为 右子节点的索引
    
        if largest != index:  # 最大值索引 不是 父节点的索引
            unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest]  # 将父节点和左右节点中的较大者互换位置
            heapify(unsorted, largest, heap_size)  # 递归的整理树的节点
    
    def heap_sort(unsorted):
        n = len(unsorted)
        for i in range(n//2 - 1, -1, -1):  # 建立初始大根堆
            heapify(unsorted, i, n)
            print(unsorted)
        for i in range(n - 1, 0, -1):  # 在原有列表的基础上,将每次大根堆的最大值和最尾部节点做交换,
            # print(f"===>{i}")
            unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
            heapify(unsorted, 0, i)  # 重新整理剩下的节点为大根堆
    
        return unsorted
    
    
    if __name__ == '__main__':
        unsorted = [3, 1, 9, 4, 2, 7, 5, 8, 6, 0]
        print(heap_sort(unsorted))
    
  • 相关阅读:
    Git删除不存在对应远程分支的本地分支
    Git删除远程分支
    将博客搬至CSDN
    HttpStatus
    Mysql 日期
    jekyll开发静态网站
    修改maven默认的jdk版本
    使用@Value进行静态常量的值注入
    妙笔生花处,惊艳四座
    Integer 和 int 值比较
  • 原文地址:https://www.cnblogs.com/yezigege/p/13386484.html
Copyright © 2011-2022 走看看