排序算法

来源:互联网 发布:深圳it 编辑:程序博客网 时间:2024/06/05 02:40

排序算法的比较

这里写图片描述

待排序list lst = [28, 35, 46, 32, 64, 21]

直接插入排序

排序思想:
假设第一个数是排序好的序列,不断从后面选取一个,插入到前面排序好的序列.

[28  35 |  46  32  64  21][28  35  46 |  32  64  21][28  32  35  46 |  64  21][28  32  35  46  64 |  21][21  28  32  35  46  64 |]

Python代码

从i为1开始遍历, 先保存lst[i]的值到temp中, 接着j = i -1 ,list[j]就是要插入元素的前一个元素. 从序号j-1 到 0 用temp和相应元素比较,如果temp小,则lst[j] 后移.最后将temp放在lst[j]位置.

# 直接插入排序 ascdef straight_insert_asc(lst):    for i in range(1, len(lst)):        temp = lst[i]        j = i-1        while j >= 0 and lst[j] > temp:            lst[j+1] = lst[j]            j -= 1        lst[j+1] = temp        print(str(lst).replace(",", " "))

Golang代码

func straightSortASC(arr []int){    for i := 1; i < len(arr) ; i++ {        temp := arr[i]        j := i -1        for j >= 0 && temp < arr[j]  {            arr[j+1] = arr[j]            j --        }        arr[j+1] = temp    }}

这里写图片描述

这里写图片描述

冒泡排序

排序思想:
从左到右,不断比较相邻两个数的大小,把大的往后方,一轮后,最大的数排在最后. 反复几轮后,顺序就排好了.

[28  35  32  46  21  | 64][28  32  35  21  | 46  64][28  32  21  | 35  46  64][28  21  | 32  35  46  64][21  | 28  32  35  46  64]

Python代码

def bubble_sort_asc(lst):    for i in range(1, len(lst)):  # i = 1~n        for j in range(len(lst)-i):  # 0~(n-i)            if lst[j] > lst[j+1]:                temp = lst[j]                lst[j] = lst[j+1]                lst[j+1] = temp   return lst

更方便记忆的算法如下:

def bubble_sort_asc(lst):    n = len(lst)    flag = False  # 设置标志位, 标记序列是否有序    while not flag:        flag = True  # 假定序列有序        for i in range(1, n):            if lst[i-1] > lst[i]:                lst[i-1], lst[i] = lst[i], lst[i-1]                flag = False         n -= 1  # 至此元素必然就位, 故可以缩短待排序序列的有效长度    return lst

Golang代码

func bubbleSortASC(lst []int){    for i := 1; i < len(lst); i++ {        for j := 0; j < len(lst)-i; j++ {            if lst[j] > lst[j+1] {                temp := lst[j]                lst[j] = lst[j+1]                lst[j+1] = temp            }        }    }}

这里写图片描述

这里写图片描述

未完待续…